<?php
ob_start();
error_reporting(0);
ini_set('display_errors', 0);

// Addressing PHPSESSID SameSite rejection
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();

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

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');
require_once('../libs/classes/MyMethods.php');

$response = ['success' => false, 'message' => ''];

try {
    $crud = new App_DB(DBU::$dba_user);
    $method = new MyMethods();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $userid = isset($_POST['admin']) ? trim($_POST['admin']) : '';
        $key = isset($_POST['userkey']) ? trim($_POST['userkey']) : '';
        $hijri_dat = isset($_POST['dat']) ? trim($_POST['dat']) : date('d-m-Y');

        if (empty($userid) || empty($key)) {
            $response['message'] = 'Please fill out all the fields.';
        } else {
            $sql = "SELECT * FROM login WHERE userid = :userid";
            $user = $crud->getRecordFilled($sql, array(':userid' => $userid));

            if ($user && ($method->verify_user($key, $user['userkey']) || $key === $user['userkey'])) {
                $_SESSION['userid'] = $userid;
                $_SESSION['key'] = $key; // Keeping for compatibility if needed
                $_SESSION['hijri'] = $hijri_dat;

                $response['success'] = true;
                $response['message'] = 'Login successful! Redirecting...';
            } else {
                $response['message'] = 'Authentication Failed. Invalid username or password.';
            }
        }
    } else {
        $response['message'] = 'Invalid request method.';
    }
} catch (Exception $e) {
    $response['message'] = 'System Error: ' . $e->getMessage();
}

echo json_encode($response);
ob_flush();
?>