<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../includes/db.php';

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

$action = isset($_GET['action']) ? $_GET['action'] : '';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($action === 'check_session') {
        if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true && isset($_SESSION['user']['username'])) {
            // Fetch fresh permissions and status from database to keep session in sync
            $username = $_SESSION['user']['username'];
            $stmt = $conn->prepare("SELECT id, name, username, status, permissions FROM users WHERE username = ?");
            $stmt->bind_param('s', $username);
            $stmt->execute();
            $res = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if ($res) {
                if ($res['status'] === 'suspended') {
                    // Account suspended in the meantime! Destroy session
                    session_destroy();
                    echo json_encode(['status' => 'unauthorized', 'message' => 'تم إيقاف حسابك من قبل الإدارة.']);
                    exit;
                }

                $user_data = [
                    'id' => $res['id'],
                    'name' => $res['name'],
                    'username' => $res['username'],
                    'status' => $res['status'],
                    'permissions' => json_decode($res['permissions'], true) ?: new stdClass()
                ];
                // Keep session updated
                $_SESSION['user'] = $user_data;

                echo json_encode([
                    'status' => 'success',
                    'user' => $_SESSION['user']
                ]);
            } else {
                session_destroy();
                echo json_encode(['status' => 'unauthorized', 'message' => 'الحساب غير موجود.']);
            }
        } else {
            echo json_encode(['status' => 'unauthorized', 'message' => 'الجلسة غير نشطة أو انتهت صلاحيتها.']);
        }
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true) ?? [];

    if ($action === 'login') {
        $username = isset($input['username']) ? trim($input['username']) : '';
        $password = isset($input['password']) ? $input['password'] : '';

        if (empty($username) || empty($password)) {
            echo json_encode(['status' => 'error', 'message' => 'يرجى إدخال اسم المستخدم وكلمة المرور.']);
            exit;
        }

        $stmt = $conn->prepare("SELECT id, name, username, password, status, permissions FROM users WHERE LOWER(username) = LOWER(?)");
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($user && password_verify($password, $user['password'])) {
            if ($user['status'] === 'suspended') {
                echo json_encode(['status' => 'error', 'message' => 'عذراً، هذا الحساب موقوف حالياً من قبل الإدارة.']);
                exit;
            }

            $user_data = [
                'id' => $user['id'],
                'name' => $user['name'],
                'username' => $user['username'],
                'status' => $user['status'],
                'permissions' => json_decode($user['permissions'], true) ?: new stdClass()
            ];

            // Store in session with regenerated ID to prevent Session Fixation
            session_regenerate_id(true);
            $_SESSION['logged_in'] = true;
            $_SESSION['user'] = $user_data;
            $_SESSION['last_activity'] = time();
            if (empty($_SESSION['csrf_token'])) {
                $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            }

            echo json_encode([
                'status' => 'success',
                'message' => 'تم تسجيل الدخول بنجاح',
                'user' => $user_data
            ]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'اسم المستخدم أو كلمة المرور غير صحيحة.']);
        }
        exit;
    }

    if ($action === 'logout') {
        // Destroy session
        $_SESSION = [];
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        session_destroy();

        echo json_encode(['status' => 'success', 'message' => 'تم تسجيل الخروج بنجاح']);
        exit;
    }
}

echo json_encode(['status' => 'error', 'message' => 'طلب غير صالح']);
?>
