<?php
header("Content-Type: application/json; charset=UTF-8");
include('last_db_config.php');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Set JSON response header
header('Content-Type: application/json');

// Secret key for encryption (change this to a strong secret)
define('SECRET_KEY', 'your_super_secret_key_2024_secure_encryption');
define('ENCRYPTION_METHOD', 'AES-256-CBC');

function encryptData($data) {
    $key = hash('sha256', SECRET_KEY);
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(ENCRYPTION_METHOD));
    $encrypted = openssl_encrypt($data, ENCRYPTION_METHOD, $key, 0, $iv);
    return base64_encode($encrypted . '::' . $iv);
}

function decryptData($data) {
    $key = hash('sha256', SECRET_KEY);
    list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
    return openssl_decrypt($encrypted_data, ENCRYPTION_METHOD, $key, 0, $iv);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $national_id = isset($_POST['national_id']) ? trim($_POST['national_id']) : '';
    $remember_me = isset($_POST['remember_me']) && $_POST['remember_me'] == '1' ? true : false;
    
    // Validate national ID
    if (empty($national_id) || strlen($national_id) !== 14 || !preg_match('/^\d{14}$/', $national_id)) {
        echo json_encode([
            'success' => false,
            'message' => 'الرجاء إدخال الرقم القومي بشكل صحيح (14 رقمًا)'
        ]);
        exit();
    }
    
    // Prepare statement to prevent SQL injection
    $stmt = $conn->prepare("SELECT Name, NationalID FROM evaluator WHERE NationalID = ?");
    $stmt->bind_param("s", $national_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        // Start session
        session_start();
        $_SESSION['evaluator_name'] = $row['Name'];
        $_SESSION['national_id'] = $row['NationalID'];
        $_SESSION['login_time'] = time();
        $_SESSION['is_authenticated'] = true;
        
        // Set cookie if "Remember Me" is checked
        if ($remember_me) {
            // Create encrypted token with user data
            $token_data = json_encode([
                'national_id' => $row['NationalID'],
                'name' => $row['Name'],
                'expires' => time() + 2592000 // 30 days
            ]);
            
            $encrypted_token = encryptData($token_data);
            
            // Set cookie for 30 days
            setcookie('auth_token', $encrypted_token, time() + 2592000, '/', '', false, true);
            setcookie('remembered_national_id', $row['NationalID'], time() + 2592000, '/', '', false, true);
            setcookie('remembered_name', $row['Name'], time() + 2592000, '/', '', false, true);
        } else {
            // Clear cookies if not remembered
            if (isset($_COOKIE['auth_token'])) {
                setcookie('auth_token', '', time() - 3600, '/');
            }
            if (isset($_COOKIE['remembered_national_id'])) {
                setcookie('remembered_national_id', '', time() - 3600, '/');
            }
            if (isset($_COOKIE['remembered_name'])) {
                setcookie('remembered_name', '', time() - 3600, '/');
            }
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'تم تسجيل الدخول بنجاح! جاري التحويل...',
            'redirect' => 'dashboard.php',
            'name' => $row['Name']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'الرقم القومي غير صحيح. يرجى التسجيل أولاً.'
        ]);
    }
    
    $stmt->close();
    $conn->close();
} else {
    echo json_encode([
        'success' => false,
        'message' => 'طلب غير صحيح'
    ]);
}
?>