<?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');

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

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

$email = $data['email'];
$password = $data['senha'];
$chromeStoreID = $data['chromeStoreID'];

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

// Connect to DB
$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"
    ]);
    exit;
}

// Get user data
$stmt = $conn->prepare("SELECT id, password, plan_expiry_date, max_devices FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows !== 1) {
    echo json_encode([
        "success" => false,
        "message" => "User not found",
        "msg_id" => "login_userNotFind"
    ]);
    exit;
}

$user = $result->fetch_assoc();

// Verify password (plain text)
if ($password !== $user['password']) {
    echo json_encode([
        "success" => false,
        "message" => "Incorrect password",
        "msg_id" => "invalid_password"
    ]);
    exit;
}

// Check plan expiry
$today = date('Y-m-d');
if ($user['plan_expiry_date'] < $today) {
    echo json_encode([
        "success" => false,
        "message" => "Please purchase a plan",
        "msg_id" => "login_userNotFind"
    ]);
    exit;
}

// Check if device already registered
$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) {
    // Count current devices
    $countStmt = $conn->prepare("SELECT COUNT(*) as total FROM user_devices WHERE user_id = ?");
    $countStmt->bind_param("i", $user['id']);
    $countStmt->execute();
    $countResult = $countStmt->get_result()->fetch_assoc();
    $totalDevices = $countResult['total'];

    if ($totalDevices >= $user['max_devices']) {
        echo json_encode([
            "success" => false,
            "message" => "Device limit reached. Please contact admin.",
            "msg_id" => "device_limit_reached"
        ]);
        exit;
    }

    // Register new device
    $registerDevice = $conn->prepare("INSERT INTO user_devices (user_id, chrome_store_id) VALUES (?, ?)");
    $registerDevice->bind_param("is", $user['id'], $chromeStoreID);
    $registerDevice->execute();
    $registerDevice->close();
}

// Generate new token
$token = bin2hex(random_bytes(16));
$updateToken = $conn->prepare("UPDATE users SET token = ? WHERE id = ?");
$updateToken->bind_param("si", $token, $user['id']);
$updateToken->execute();
$updateToken->close();

// Success response
echo json_encode([
    "success" => true,
    "message" => "Login realizado com sucesso",
    "msg_id" => "login_success",
    "token" => $token,
    "sigeID" => $user['id']
]);

// Close everything
$stmt->close();
$conn->close();
?>
