<?php
// card_printing_login.php - CARD PRINTING ONLY VERSION
error_reporting(0);
ini_set('display_errors', 0);

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if already logged in as card_printing
if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'card_printing') {
    header("Location: card_printing_dashboard.php");
    exit;
}

// If logged in with other role, destroy session
if (isset($_SESSION['user_role']) && $_SESSION['user_role'] !== 'card_printing') {
    session_destroy();
    session_start();
}

// Simple database connection
require 'db.php';
@$mysqli1->set_charset('utf8mb4');

// Define card printing role ONLY
$role_info = [
    'name' => 'طباعة البطاقات',
    'color' => '#f39c12',
    'icon' => 'fas fa-id-card',
    'role' => 'card_printing'
];

// Initialize variables
$error = $username = '';

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $role = 'card_printing'; // Force card_printing role
    
    // Validation
    if (empty($username) || empty($password)) {
        $error = 'اسم المستخدم وكلمة المرور مطلوبان';
    } else {
        // Check for card_printing user (role_id = 4)
        $stmt = @$mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, role_id FROM committee_users WHERE username = ? AND role_id = 4 LIMIT 1");
        if ($stmt) {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();
            $user = $result->fetch_assoc();
            $stmt->close();
            
            if ($user) {
                // Check password
                if (password_verify($password, $user['password_hash']) || $user['password_hash'] === $password) {
                    $_SESSION['committee_id'] = $user['id'];
                    $_SESSION['committee_username'] = $user['username'];
                    $_SESSION['committee_name'] = $user['name'];
                    $_SESSION['committee_can_all'] = ($user['can_view_all'] == 1);
                    $_SESSION['committee_role_id'] = $user['role_id']; // Should be 4
                    $_SESSION['user_role'] = 'card_printing';
                    
                    header("Location: card_printing_dashboard.php");
                    exit;
                } else {
                    $error = 'كلمة المرور غير صحيحة';
                }
            } else {
                // Check if user exists but has wrong role_id
                $stmt2 = @$mysqli1->prepare("SELECT username FROM committee_users WHERE username = ? LIMIT 1");
                if ($stmt2) {
                    $stmt2->bind_param("s", $username);
                    $stmt2->execute();
                    $result2 = $stmt2->get_result();
                    $user_exists = $result2->num_rows > 0;
                    $stmt2->close();
                    
                    if ($user_exists) {
                        $error = 'المستخدم ليس لديه صلاحية طباعة البطاقات (role_id يجب أن يكون 4)';
                    } else {
                        $error = 'اسم المستخدم غير موجود';
                    }
                } else {
                    $error = 'اسم المستخدم غير موجود';
                }
            }
        } else {
            $error = 'خطأ في النظام';
        }
    }
}

// Check if card_printing user exists in database, if not, create one
$result = @$mysqli1->query("SELECT id FROM committee_users WHERE role_id = 4 LIMIT 1");
if (!$result || $result->num_rows === 0) {
    // Create default card printing user
    $default_password = 'cardprint#123';
    $hash = password_hash($default_password, PASSWORD_DEFAULT);
    $insert_query = "INSERT INTO committee_users (username, password_hash, name, can_view_all, role_id, role_name, created_at) 
                    VALUES ('card_printer', '$hash', 'طباعة البطاقات', 1, 4, 'card_printing', NOW())";
    @$mysqli1->query($insert_query);
}

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل الدخول - نظام طباعة البطاقات</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Cairo', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .login-container {
            width: 100%;
            max-width: 400px;
        }
        .login-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            text-align: center;
        }
        .header-icon {
            background: #f39c12;
            color: white;
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 2rem;
        }
        .login-title {
            text-align: center;
            margin-bottom: 25px;
            color: #333;
            font-size: 1.5rem;
        }
        .login-subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 1rem;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 600;
            text-align: right;
        }
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            font-family: 'Cairo', sans-serif;
            transition: border-color 0.3s;
        }
        .form-control:focus {
            outline: none;
            border-color: #f39c12;
        }
        .input-with-icon {
            position: relative;
        }
        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }
        .btn-login {
            width: 100%;
            padding: 14px;
            background: #f39c12;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1.1rem;
            font-weight: 700;
            cursor: pointer;
            transition: background 0.3s;
            margin-top: 10px;
        }
        .btn-login:hover {
            background: #e67e22;
        }
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
            text-align: center;
        }
        .system-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            text-align: center;
            border: 1px dashed #dee2e6;
            font-size: 0.9rem;
            color: #6c757d;
        }
        .password-toggle {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            cursor: pointer;
        }
        .default-user {
            background: #e8f4fd;
            border-radius: 8px;
            padding: 12px;
            margin-top: 20px;
            text-align: center;
            border: 1px solid #b3d9ff;
            font-size: 0.85rem;
        }
        .cred-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            font-family: monospace;
        }
        @media (max-width: 480px) {
            .login-card { padding: 20px; }
            .header-icon { width: 60px; height: 60px; font-size: 1.5rem; }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <!-- Header Icon -->
            <div class="header-icon">
                <i class="fas fa-id-card"></i>
            </div>
            
            <!-- Title -->
            <h2 class="login-title">نظام طباعة البطاقات</h2>
            <div class="login-subtitle">تسجيل الدخول لموظفي طباعة البطاقات فقط</div>
            
            <!-- Error Message -->
            <?php if ($error): ?>
                <div class="alert">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <!-- Login Form -->
            <form method="post">
                <input type="hidden" name="role" value="card_printing">
                
                <div class="form-group">
                    <label class="form-label">
                        <i class="fas fa-user"></i> اسم المستخدم
                    </label>
                    <div class="input-with-icon">
                        <input type="text" 
                               class="form-control" 
                               name="username" 
                               value="<?php echo htmlspecialchars($username); ?>"
                               placeholder="أدخل اسم المستخدم"
                               required
                               autofocus>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">
                        <i class="fas fa-lock"></i> كلمة المرور
                    </label>
                    <div class="input-with-icon">
                        <input type="password" 
                               class="form-control" 
                               name="password" 
                               placeholder="أدخل كلمة المرور"
                               required
                               id="passwordInput">
                        <span class="password-toggle" id="togglePassword">
                            <i class="fas fa-eye"></i>
                        </span>
                    </div>
                </div>
                
                <button type="submit" class="btn-login">
                    <i class="fas fa-sign-in-alt"></i> دخول لطباعة البطاقات
                </button>
            </form>
            
          
            <!-- System Info -->
            <div class="system-info">
                <i class="fas fa-info-circle"></i> نظام خاص بطباعة وإصدار البطاقات الجامعية
            </div>
        </div>
    </div>

    <script>
        // Toggle password visibility
        document.getElementById('togglePassword').addEventListener('click', function() {
            const passwordInput = document.getElementById('passwordInput');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
        
        // Auto-focus on username
        document.querySelector('input[name="username"]').focus();
    </script>
</body>
</html>