<?php
require_once 'config.php';
require 'jwt/autoload.php'; // JWT Composer
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

header('Content-Type: application/json');

// Strong static secret key (same as signup.php)
$jwt_secret = "Shuvo_2025_SECURE49797567697979696967676967696979797969796f796f796f";

// ========================
// 🔧 TOGGLE TOKEN REGENERATION
// true  → generate a new JWT on every login (current behaviour)
// false → keep the token unchanged after first generation
// ========================
$ALLOW_TOKEN_REGEN = false;   // <-- change this to false to freeze tokens

// ========================
// Main Login Logic
// ========================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username  = trim($_POST['username'] ?? '');
    $password  = trim($_POST['password'] ?? '');
    $fcm_key   = trim($_POST['fcm_key'] ?? '');
    $device_id = trim($_POST['DeVicE_iD'] ?? '');

    if (empty($username) || empty($password) || empty($device_id)) {
        echo json_encode([
            "status"  => "error",
            "message" => "Missing required fields"
        ]);
        $conn->close();
        exit;
    }

    // ✅ Step 1: Get user by username & password (plain text – keep as is)
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
    if (!$stmt) {
        echo json_encode([
            "status"  => "error",
            "message" => "Prepare failed: " . $conn->error
        ]);
        $conn->close();
        exit;
    }

    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $result = $stmt->get_result();

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

        // ✅ Step 2: Check multiple_login from appinfo
        $ml_stmt = $conn->prepare("SELECT multiple_login FROM appinfo LIMIT 1");
        $ml_stmt->execute();
        $ml_result = $ml_stmt->get_result();
        $ml_row = $ml_result->fetch_assoc();
        $ml_stmt->close();
        $multiple_login = $ml_row['multiple_login'] ?? 'NO';

        // ✅ Step 3: Device ID check (skip if multiple_login is ON)
        if ($multiple_login === 'ON' || $user['device_id'] === $device_id) {

            // ✅ Step 4: Update FCM key (always)
            $update_stmt = $conn->prepare("UPDATE users SET fcm_key = ? WHERE username = ?");
            $update_stmt->bind_param("ss", $fcm_key, $username);
            $update_stmt->execute();
            $update_stmt->close();

            // ✅ Step 5: Handle token based on $ALLOW_TOKEN_REGEN
            $token = null;

            if ($ALLOW_TOKEN_REGEN === true) {
                // Generate a brand new token and store it
                $payload = [
                    'email'     => $user['email'],
                    'device_id' => $device_id,
                    'iat'       => time()
                ];
                $token = JWT::encode($payload, $jwt_secret, 'HS256');

                // Save the new token in the database
                $token_stmt = $conn->prepare("UPDATE users SET token = ? WHERE username = ?");
                $token_stmt->bind_param("ss", $token, $username);
                $token_stmt->execute();
                $token_stmt->close();

            } else {
                // Token regeneration is OFF – reuse existing token if available
                if (!empty($user['token'])) {
                    $token = $user['token'];
                } else {
                    // First login for this user – generate a token and store it
                    $payload = [
                        'email'     => $user['email'],
                        'device_id' => $device_id,
                        'iat'       => time()
                    ];
                    $token = JWT::encode($payload, $jwt_secret, 'HS256');

                    $token_stmt = $conn->prepare("UPDATE users SET token = ? WHERE username = ?");
                    $token_stmt->bind_param("ss", $token, $username);
                    $token_stmt->execute();
                    $token_stmt->close();
                }
            }

            // ✅ Step 6: Return response
            echo json_encode([
                "status"   => "success",
                "message"  => "Login Success",
                "username" => $user['username'],
                "fcm_key"  => $fcm_key,
                "token"    => $token
            ]);

        } else {
            echo json_encode([
                "status"  => "error",
                "message" => "Invalid Device ID"
            ]);
        }

    } else {
        echo json_encode([
            "status"  => "error",
            "message" => "Wrong Username or Password"
        ]);
    }

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

} else {
    echo json_encode([
        "status"  => "error",
        "message" => "Invalid Request"
    ]);
}
?>