<?php
require '../../../vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

header("Content-Type: application/json");
include_once("../config.php");


$secret_key = "theWatify$2025@#"; 
$issuer = "app.watify.io"; 
$cookie_expiry = time() + 3600 * 24 *30; 

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data["emailaddress"]) || !isset($data["password"])) {
    echo json_encode(["status" => "error", "message" => "Missing email or password"]);
    exit();
}

$email = $data["emailaddress"];
$enteredPassword = $data["password"];

// Fetch user details including role
$stmt = $db->prepare("SELECT id, name, email, phone, password, role, client_id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();

    if (password_verify($enteredPassword, $user["password"])) {

        $roles = $user["role"];
        $sql = "SELECT DISTINCT page FROM role_based_access WHERE FIND_IN_SET(role, ?)";
        $stmt = $db->prepare($sql);
        $stmt->bind_param("s", $roles);
        $stmt->execute();
        $pagesResult = $stmt->get_result();

        $pages = [];
        while ($row = $pagesResult->fetch_assoc()) {
            $pages[] = $row["page"];
        }

        // Generate JWT with role
        $payload = [
            "iss" => $issuer,         
            "iat" => time(),          
            "exp" => $cookie_expiry,  
            "user_id" => $user["id"],
            "client_id" => $user["client_id"],
            "name" => $user["name"],
            "email" => $user["email"],
            "phone" => $user["phone"],
            // "role" => $user["role"], 
            // "page" => $pages
        ];

        $token = JWT::encode($payload, $secret_key, 'HS256'); 
        // Set JWT in HTTP-only cookie
          
        setcookie("auth_token", $token, [
            "expires" => $cookie_expiry,
            "path" => "/",
            "domain" => "app.watify.io",
            "secure" => true,
            "httponly" => true,
            "samesite" => "Strict"
        ]);

        echo json_encode(["status" => "success", "message" => "Login successful", "pages" => $pages]);
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid credentials"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Invalid credentials"]);
}
$stmt->close();
$db->close();
?>
