<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(5);

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

// Log request
file_put_contents(__DIR__ . "/login_debug.log", "\n" . date('Y-m-d H:i:s') . " - NEW REQUEST\n", FILE_APPEND);

if (!isset($_POST['mobile']) || !isset($_POST['password'])) {
    echo json_encode(["status" => 0, "msg" => "Missing credentials"]);
    exit;
}

file_put_contents(__DIR__ . "/login_debug.log", "Credentials received\n", FILE_APPEND);

try {
    require_once '../config.php';
    file_put_contents(__DIR__ . "/login_debug.log", "Config loaded\n", FILE_APPEND);
} catch (Exception $e) {
    echo json_encode(["status" => 0, "msg" => "Config error: " . $e->getMessage()]);
    exit;
}

$username = mysqli_real_escape_string($conn, $_POST['mobile']);
$password = $_POST['password']; 

file_put_contents(__DIR__ . "/login_debug.log", "About to query for: $username\n", FILE_APPEND);

$query = "SELECT id, password, acc_ban FROM users WHERE mobile = '$username' LIMIT 1";

try {
    $run = mysqli_query($conn, $query);
    file_put_contents(__DIR__ . "/login_debug.log", "Query executed\n", FILE_APPEND);
} catch (Exception $e) {
    file_put_contents(__DIR__ . "/login_debug.log", "Query error: " . $e->getMessage() . "\n", FILE_APPEND);
    echo json_encode(["status" => 0, "msg" => "Query error"]);
    exit;
}

if (!$run) {
    file_put_contents(__DIR__ . "/login_debug.log", "Query failed: " . mysqli_error($conn) . "\n", FILE_APPEND);
    echo json_encode(["status" => 0, "msg" => "Query failed"]);
    exit;
}

file_put_contents(__DIR__ . "/login_debug.log", "Checking rows\n", FILE_APPEND);

if (mysqli_num_rows($run) > 0) {
    $row = mysqli_fetch_array($run);
    file_put_contents(__DIR__ . "/login_debug.log", "User found\n", FILE_APPEND);
    
    if ($row['acc_ban'] == 'on') {
        echo json_encode(["status" => 5, "msg" => 'Account locked']);
        exit;
    }

    if (password_verify($password, $row['password'])) {
        file_put_contents(__DIR__ . "/login_debug.log", "Password verified\n", FILE_APPEND);
        
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        $_SESSION['username'] = $username;
        $_SESSION['user_id'] = $row['id'];
        $_SESSION['login_time'] = time();
        
        file_put_contents(__DIR__ . "/login_debug.log", "Login successful\n", FILE_APPEND);
        echo json_encode(["status" => 11, "msg" => 'login success', "userid" => $row['id']]);
        exit;
    } else {
        file_put_contents(__DIR__ . "/login_debug.log", "Password incorrect\n", FILE_APPEND);
        echo json_encode(["status" => 2, "msg" => 'Invalid password']);
        exit;
    }
} else {
    file_put_contents(__DIR__ . "/login_debug.log", "User not found\n", FILE_APPEND);
    echo json_encode(["status" => 4, "msg" => 'Username does not exist']);
    exit;
}
?>
