<?php
require_once 'conn.php';
session_start();

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

function sendResponse($success, $message, $data = []) {
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

if (!isset($_POST['email']) || !isset($_POST['password'])) {
    sendResponse(false, 'Please provide email and password');
}

$email = trim(strtolower(mysqli_real_escape_string($conn, $_POST['email'])));
$pass = trim(strtolower(mysqli_real_escape_string($conn, $_POST['password'])));

if (empty($email)) {
    sendResponse(false, 'Please enter your email or username');
}

if (empty($pass)) {
    sendResponse(false, 'Password field is required');
}

// Check if input is email or username
$q = "SELECT email, uname, pass, email_verified, lock_account FROM info WHERE email = '$email' OR uname = '$email'";
$r = mysqli_query($conn, $q);

if (mysqli_num_rows($r) === 0) {
    sendResponse(false, 'Invalid login credentials');
}

$row = mysqli_fetch_assoc($r);
$db_email = $row['email'];
$db_pass = strtolower($row['pass']);
$email_verified = $row['email_verified'];
$lock_account = $row['lock_account'];

if ($lock_account == 1) {
    sendResponse(false, 'Your account is temporarily locked. Contact support@speedbitplus.com for assistance');
}

if ($db_pass !== strtolower($pass)) {
    sendResponse(false, 'Invalid login password');
}

if ($email_verified != 1) {
    include_once('../include/mail.php');
    $_SESSION['user_registered'] = true;
    sendResponse(false, 'We’ve sent a verification email to your registered address. Check your inbox or spam folder to activate your account.');
}

$_SESSION['user_id'] = md5(strtolower($db_email));
sendResponse(true, 'Login successful', ['redirect' => '/user']);
?>