<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header('Content-Type: application/json');

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

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

if (!isset($data['email'], $data['token'], $data['chromeStoreID'])) {
    echo json_encode([
        "success" => false,
        "message" => "Missing required fields",
        "msg_id" => "missing_fields",
        "sigeID" => null
    ]);
    exit;
}

$email = $data['email'];
$token = $data['token'];
$chromeStoreID = $data['chromeStoreID'];

// DB config
$host = 'localhost';
$db = 'deivis_panelcrm';
$user = 'deivis_panelcrm';
$pass = 'deivis_panelcrm';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    echo json_encode([
        "success" => false,
        "message" => "Database connection failed",
        "msg_id" => "db_connection_error",
        "sigeID" => null
    ]);
    exit;
}

// Fetch user by email and token, include expiry date
$stmt = $conn->prepare("SELECT id, token, plan_expiry_date FROM users WHERE email = ? AND token = ?");
$stmt->bind_param("ss", $email, $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows !== 1) {
    echo json_encode([
        "success" => false,
        "message" => "Erro - Sessão inválida.",
        "msg_id" => "user_login_notFound",
        "sigeID" => null
    ]);
    exit;
}

$user = $result->fetch_assoc();

// 🔐 Expiry date check
$currentDate = date('Y-m-d');
if ($user['plan_expiry_date'] < $currentDate) {
    echo json_encode([
        "success" => false,
        "message" => "Erro - Sessão inválida.",
        "msg_id" => "user_login_notFound",
        "sigeID" => null
    ]);
    exit;
}

// Optional: check if chromeStoreID is registered device
$deviceCheck = $conn->prepare("SELECT id FROM user_devices WHERE user_id = ? AND chrome_store_id = ?");
$deviceCheck->bind_param("is", $user['id'], $chromeStoreID);
$deviceCheck->execute();
$deviceResult = $deviceCheck->get_result();

if ($deviceResult->num_rows === 0) {
    echo json_encode([
        "success" => false,
        "message" => "Erro - Dispositivo não autorizado.",
        "msg_id" => "device_not_authorized",
        "sigeID" => $user['id']
    ]);
    exit;
}

// ✅ Success
echo json_encode([
    "success" => true,
    "message" => "Sucesso - Token válido.",
    "msg_id" => "login_success",
    "sigeID" => $user['id']
]);

$stmt->close();
$conn->close();
?>
