<?php
// 1. Set CORS and Header configuration
header("Access-Control-Allow-Origin: http://51.79.53.46:8080");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/../services/db.php';

$conn = db();

if (!$conn) {
    http_response_code(500);
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}

// 2. Read JSON body safely
$raw = file_get_contents("php://input");
$input = json_decode($raw, true);

if (!$input || empty($input['email']) || empty($input['password'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing credentials"]);
    exit;
}

$email = $input['email'];
$password = $input['password'];

// 3. Query user
$sql = "SELECT id, email, name, password_hash FROM users WHERE email = ?";
$stmt = sqlsrv_query($conn, $sql, [$email]);

if ($stmt === false) {
    http_response_code(500);
    echo json_encode(["error" => "DB query failed", "details" => sqlsrv_errors()]);
    exit;
}

$user = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

if (!$user || !password_verify($password, $user['password_hash'])) {
    http_response_code(401);
    echo json_encode(["error" => "Invalid email or password"]);
    exit;
}

// 4. Generate session token
$token = bin2hex(random_bytes(32));

// 5. Store session in MSSQL DB
$sql = "INSERT INTO sessions (user_id, token, created_at) VALUES (?, ?, GETDATE())";
$stmt = sqlsrv_query($conn, $sql, [$user['id'], $token]);

if ($stmt === false) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to save session", "details" => sqlsrv_errors()]);
    exit;
}

// 6. Set cookie for ALL routes under /HZ-ProjectHub-v2/
setcookie(
    "session",
    $token,
    [
        "expires"  => time() + 86400,
        "path"     => "/HZ-ProjectHub-v2/", // 👈 FIX: Matches your actual project path!
        "httponly" => false,
        "samesite" => "Lax"
    ]
);

// 7. Success response (including token in JSON payload for localStorage)
echo json_encode([
    "success" => true,
    "token"   => $token, // 👈 FIX: Returns token so Frontend localStorage receives it!
    "user"    => [
        "id"    => (int)$user['id'],
        "email" => $user['email'],
        "name"  => $user['name']
    ]
]);