<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }
header('Content-Type: application/json');

include_once '../config/Database.php';
include_once '../config/config.php';
require_once '../vendor/autoload.php';
use Firebase\JWT\JWT;

$database = new Database();
$db = $database->connect();
$data = json_decode(file_get_contents("php://input"));

if (!isset($data->email) || !isset($data->password)) {
    http_response_code(400);
    echo json_encode(['message' => 'Email and password are required.']);
    exit();
}

$query = 'SELECT * FROM users WHERE email = :email LIMIT 1';
$stmt = $db->prepare($query);
$stmt->bindParam(':email', $data->email);
$stmt->execute();

if ($stmt->rowCount() == 1) {
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (password_verify($data->password, $user['password'])) {
        $payload = [
            'iss' => "salenecredit.co.ke", 'iat' => time(), 'exp' => time() + (60 * 60 * 24),
            'data' => [ 'id' => $user['id'], 'name' => $user['name'], 'email' => $user['email'], 'role' => $user['role'] ]
        ];
        $jwt = JWT::encode($payload, JWT_SECRET, 'HS256');
        echo json_encode([ 'token' => $jwt, 'user' => $payload['data'] ]);
    } else {
        http_response_code(401);
        echo json_encode(['message' => 'Invalid credentials.']);
    }
} else {
    http_response_code(401);
    echo json_encode(['message' => 'Invalid credentials.']);
}
?>