<?php
// ─── Authentication API ──────────────────────────────────────────────────────

function login() {
    global $conn;
    
    $email = strtolower(trim($_POST['email'] ?? ''));
    $pass  = $_POST['pass'] ?? '';
    $url   = $_POST['url'] ?? '';
    
    if ($email === '' || $pass === '') {
        error_response('Please enter both email and password.');
    }
    
    // Check lockout
    if (!isset($_SESSION['login_attempts'])) $_SESSION['login_attempts'] = [];
    if (isset($_SESSION['login_attempts'][$email]) && $_SESSION['login_attempts'][$email] >= 5) {
        success_response(['locked' => true], 'Account locked. Please reset your password.');
    }
    
    // Validate credentials
    $emailSafe = mysqli_real_escape_string($conn, $email);
    $rsu = mysqli_query($conn, "SELECT id, name, status, pass FROM h_user WHERE email='$emailSafe'");
    $row = mysqli_fetch_assoc($rsu);
    if ($row && !check_password($pass, $row['pass'], $row['id'])) $row = null;

    if ($row) {
        unset($_SESSION['login_attempts'][$email]);
        $_SESSION['idx']  = encode($row['id'], KEY_TWO);
        $_SESSION['name'] = $row['name'];
        
        $redirect = !empty($url) ? decode($url, KEY_ONE) : 'dashboard';
        if (strpos($redirect, '://') !== false) $redirect = 'dashboard';
        
        success_response(['redirect' => $redirect]);
    } else {
        $_SESSION['login_attempts'][$email] = ($_SESSION['login_attempts'][$email] ?? 0) + 1;
        
        if ($_SESSION['login_attempts'][$email] >= 5) {
            success_response(['locked' => true], 'Account locked. Please reset your password.');
        } else {
            $remaining = max(0, 5 - $_SESSION['login_attempts'][$email]);
            success_response(
                ['attempts_left' => $remaining],
                'Invalid email or password. Attempts left: ' . $remaining
            );
        }
    }
}

function checkLock() {
    $email = strtolower(trim($_POST['email'] ?? ''));
    $locked = isset($_SESSION['login_attempts'][$email]) && $_SESSION['login_attempts'][$email] >= 5;
    success_response([
        'locked' => $locked,
        'message' => $locked ? 'Account locked. Please reset your password.' : ''
    ]);
}

function register() {
    global $conn, $now;
    
    $fname   = ucfirst(trim($_POST['fname'] ?? ''));
    $lname   = ucfirst(trim($_POST['lname'] ?? ''));
    $uname   = $fname . ' ' . $lname;
    $email   = strtolower(trim($_POST['email'] ?? ''));
    $phone   = trim($_POST['phone'] ?? '');
    $pass    = $_POST['pass'] ?? '';
    $pass2   = $_POST['pass2'] ?? '';
    $code    = trim($_POST['code'] ?? '');
    $codeok  = trim($_POST['codeok'] ?? '');
    
    // Validation
    $errors = [];
    if (empty($fname) || empty($lname) || empty($email) || empty($pass)) {
        $errors[] = 'Please fill in all required fields.';
    }
    if ($pass !== $pass2) {
        $errors[] = 'Passwords do not match.';
    }
    if (strlen($pass) < 6) {
        $errors[] = 'Password must be at least 6 characters.';
    }
    if (!empty($codeok) && decode($codeok, KEY_ONE) != $code) {
        $errors[] = 'Invalid CAPTCHA code.';
    }
    
    // Check duplicate email
    $emailSafe = mysqli_real_escape_string($conn, $email);
    $rse = mysqli_query($conn, "SELECT id FROM h_user WHERE email='$emailSafe'");
    if (mysqli_num_rows($rse) > 0) {
        $errors[] = 'Email already registered.';
    }
    
    if (!empty($errors)) {
        error_response(implode(' ', $errors));
    }
    
    // Create user
    $passok = password_hash($pass, PASSWORD_DEFAULT);
    $nameSafe = mysqli_real_escape_string($conn, $uname);
    $phoneSafe = mysqli_real_escape_string($conn, $phone);
    
    mysqli_query($conn, "INSERT INTO h_user (name, email, pass, phone, status, date) 
        VALUES ('$nameSafe', '$emailSafe', '$passok', '$phoneSafe', '0', '$now')");
    
    $uid = mysqli_insert_id($conn);
    $_SESSION['idx'] = encode($uid, KEY_TWO);
    $_SESSION['name'] = $uname;
    
    // Send verification email
    $body = "Thank you for creating a Host25Cent.com account.<br><br>"
          . "Please visit the link below to verify your email address.<br><br>"
          . "https://host25cent.com/?p=login&vid=" . encode($email, KEY_ONE) . "<br><br>"
          . "Support<br>Host25Cent.com";
    
    require_once __DIR__ . '/../config/mail.php';
    $mail = make_mailer('info@host25cent.com', 'Host25Cent', 'info@host25cent.com');
    $mail->AddAddress('berlikplc@gmail.com');
    $mail->AddAddress($email);
    $mail->Subject = 'Confirm Your Registration';
    $mail->MsgHTML($body);
    $mail->IsHTML(true);
    $mail->Send();
    
    success_response([], 'Registration successful. Please check your email to verify your account.');
}

function forgot() {
    global $conn;
    
    $emailInput = strtolower(trim($_POST['email'] ?? ''));
    $emailInput = mysqli_real_escape_string($conn, $emailInput);
    $rmo = mysqli_query($conn, "SELECT id, name FROM h_user WHERE email='$emailInput'");
    $srmo = mysqli_fetch_assoc($rmo);
    
    if (!$srmo) {
        success_response([], 'If the email exists, a reset link has been sent.');
    }
    
    $rid   = encode($srmo['id'], KEY_ONE);
    $eml   = encode($emailInput, KEY_ONE);
    $time  = encode(time(), KEY_ONE);
    
    $body = "Dear {$srmo['name']}<br><br>"
          . "Forgot your password? Reset it by clicking the link below.<br><br>"
          . "https://host25cent.com/?p=forgot&eml=$eml&rid=$rid&tt=$time&ch=pas<br><br>"
          . "This link is valid for 10 minutes.<br><br>Host25Cent.com";
    
    require_once __DIR__ . '/../config/mail.php';
    $mail = make_mailer('info@host25cent.com', 'Host25Cent', 'info@host25cent.com');
    $mail->AddAddress('berlikplc@gmail.com');
    $mail->AddAddress($emailInput);
    $mail->Subject = 'Password Reset Request';
    $mail->MsgHTML($body);
    $mail->IsHTML(true);
    $mail->Send();
    
    success_response([], 'If the email exists, a reset link has been sent.');
}

function passwordReset() {
    global $conn;
    
    $patt = decode($_POST['tt'] ?? '', KEY_ONE) + 600;
    if ($patt < time()) {
        error_response('Reset link expired. Please try again.');
    }
    
    $rid   = (int) decode($_POST['rid'] ?? '', KEY_ONE);
    $eml   = mysqli_real_escape_string($conn, decode($_POST['eml'] ?? '', KEY_ONE));
    $pass1 = $_POST['pass1'] ?? '';
    $pass2 = $_POST['pass2'] ?? '';
    
    if ($pass1 !== $pass2 || strlen($pass1) < 6) {
        error_response('Passwords do not match or too short.');
    }
    
    $passok = password_hash($pass2, PASSWORD_DEFAULT);
    $rs = mysqli_query($conn, "SELECT id FROM h_user WHERE email='$eml'");
    if (mysqli_num_rows($rs) > 0) {
        mysqli_query($conn, "UPDATE h_user SET pass='$passok' WHERE id=$rid");
        success_response([], 'Password updated successfully.');
    }
    
    error_response('User not found.');
}

function emailLink() {
    global $conn;
    
    $emailInput = strtolower(trim($_POST['email'] ?? ''));
    $emailInput = mysqli_real_escape_string($conn, $emailInput);
    $rmo = mysqli_query($conn, "SELECT id, name FROM h_user WHERE email='$emailInput'");
    $srmo = mysqli_fetch_assoc($rmo);
    
    if ($srmo) {
        $rid   = encode($srmo['id'], KEY_ONE);
        $eml   = encode($emailInput, KEY_ONE);
        $time  = encode(time() + 3600, KEY_ONE);
        
        $body = "Dear {$srmo['name']}<br><br>"
              . "Click the link below to log in.<br><br>"
              . "https://host25cent.com/?elogin=$eml&rid=$rid&tt=$time<br><br>"
              . "Valid for 1 hour.<br><br>Host25Cent.com";
        
        require_once __DIR__ . '/../config/mail.php';
        $mail = make_mailer('info@host25cent.com', 'Host25Cent', 'info@host25cent.com');
        $mail->AddAddress('berlikplc@gmail.com');
        $mail->AddAddress($emailInput);
        $mail->Subject = 'Login by Email Link';
        $mail->MsgHTML($body);
        $mail->IsHTML(true);
        $mail->Send();
    }
    
    success_response([], 'If the email exists, a login link has been sent.');
}

function verify() {
    global $conn;
    
    $vid = decode($_GET['vid'] ?? '', KEY_ONE);
    $vid = mysqli_real_escape_string($conn, $vid);
    $rs = mysqli_query($conn, "SELECT id FROM h_user WHERE email='$vid' AND status='0'");
    
    if (mysqli_num_rows($rs) > 0) {
        mysqli_query($conn, "UPDATE h_user SET status='1' WHERE email='$vid' AND status='0'");
        success_response([], 'Email verified successfully.');
    }
    
    error_response('Invalid or already verified link.', 400);
}

function logout() {
    session_destroy();
    success_response([], 'Logged out successfully.');
}