<?php
// accountant_dashboard.php - ACCOUNTANT ONLY VERSION
error_reporting(1);
ini_set('display_errors', 1);

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

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

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

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

// Define accountant role ONLY
$role_info = [
    'name' => 'المحاسب',
    'color' => '#27ae60',
    'icon' => 'fas fa-calculator',
    'role' => 'accountant'
];

// 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 = 'accountant'; // Force accountant role
    
    // Validation
    if (empty($username) || empty($password)) {
        $error = 'اسم المستخدم وكلمة المرور مطلوبان';
    } else {
        // Check for accountant user
        $stmt = @$mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, role_id FROM committee_users WHERE username = ? AND role_name = 'accountant' 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['user_role'] = 'accountant';
                    
                    header("Location: accountant_dashboard.php");
                    exit;
                } else {
                    $error = 'كلمة المرور غير صحيحة';
                }
            } else {
                $error = 'اسم المستخدم غير موجود أو ليس لديك صلاحية كـ محاسب';
            }
        } else {
            $error = 'خطأ في النظام';
        }
    }
}

// Check if accountant user exists in database, if not, create one
$result = @$mysqli1->query("SELECT id FROM committee_users WHERE role_name = 'accountant' LIMIT 1");
if (!$result || $result->num_rows === 0) {
    // Create default accountant user
    $default_password = 'accountant#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 ('accountant', '$hash', 'محاسب النظام', 1, 2, 'accountant', 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: #27ae60;
            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: #27ae60;
        }
        .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: #27ae60;
            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: #219653;
        }
        .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;
        }
        @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-calculator"></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="accountant">
                
                <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>