<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Database file paths
$usersFile = __DIR__ . '/data/users.json';
$tokensFile = __DIR__ . '/data/verification_tokens.json';

// Integrate Email System
if (file_exists(__DIR__ . '/mail.php')) {
    require_once __DIR__ . '/mail.php';
}

// Ensure data directory exists
if (!is_dir(__DIR__ . '/data')) {
    mkdir(__DIR__ . '/data', 0755, true);
}

// Initialize files if they don't exist
if (!file_exists($usersFile)) {
    file_put_contents($usersFile, json_encode([], JSON_PRETTY_PRINT));
}
if (!file_exists($tokensFile)) {
    file_put_contents($tokensFile, json_encode([], JSON_PRETTY_PRINT));
}

// Helper functions
function loadUsers()
{
    global $usersFile;
    $data = file_get_contents($usersFile);
    return json_decode($data, true) ?: [];
}

function saveUsers($users)
{
    global $usersFile;
    file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT));
}

function loadTokens()
{
    global $tokensFile;
    $data = file_get_contents($tokensFile);
    return json_decode($data, true) ?: [];
}

function saveTokens($tokens)
{
    global $tokensFile;
    file_put_contents($tokensFile, json_encode($tokens, JSON_PRETTY_PRINT));
}

function generateToken()
{
    return bin2hex(random_bytes(32));
}

// Helper functions (Updated to use real mail)
function sendVerificationEmail($email, $username, $token)
{
    // Generate Verify Link
    $verifyLink = "http://" . $_SERVER['HTTP_HOST'] . "/Gwap/verify.php?token=" . $token;

    // Email Body
    $subject = "Verify Your GadgetGo Account";
    $body = "
        <div style='text-align: center;'>
            <h2>Welcome to GadgetGo, $username!</h2>
            <p>Please click the button below to verify your email address and activate your account.</p>
            <br>
            <a href='$verifyLink' style='background-color: #135bec; color: #fff; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold;'>Verify Email</a>
            <br><br>
            <p style='font-size: 12px; color: #666;'>Or copy this link: <br>$verifyLink</p>
        </div>
    ";

    // Try sending real email via mail.php logic
    if (function_exists('send_gadget_email')) {
        send_gadget_email($email, $subject, $body);
    }

    // Log to file for development (Always keep this as fallback/debug)
    $logFile = __DIR__ . '/data/email_log.txt';
    $message = "\n\n=== VERIFICATION EMAIL ===\n";
    $message .= "To: $email\n";
    $message .= "Username: $username\n";
    $message .= "Verification Link: $verifyLink\n";
    $message .= "Time: " . date('Y-m-d H:i:s') . "\n";
    $message .= "========================\n";

    file_put_contents($logFile, $message, FILE_APPEND);

    return true;
}

// Handle different actions
$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'signup':
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $whatsapp = trim($_POST['whatsapp'] ?? '');
        $password = $_POST['password'] ?? '';

        // Validation
        if (empty($username) || empty($email) || empty($whatsapp) || empty($password)) {
            echo json_encode(['success' => false, 'error' => 'All fields are required']);
            exit;
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(['success' => false, 'error' => 'Invalid email format']);
            exit;
        }

        if (strlen($password) < 8) {
            echo json_encode(['success' => false, 'error' => 'Password must be at least 8 characters']);
            exit;
        }

        // Check for existing users
        $users = loadUsers();
        foreach ($users as $user) {
            if (strtolower($user['email']) === strtolower($email)) {
                echo json_encode(['success' => false, 'error' => 'Email already registered']);
                exit;
            }
            if (strtolower($user['username']) === strtolower($username)) {
                echo json_encode(['success' => false, 'error' => 'Username already taken']);
                exit;
            }
            if ($user['whatsapp'] === $whatsapp) {
                echo json_encode(['success' => false, 'error' => 'WhatsApp number already registered']);
                exit;
            }
        }

        // Create new user
        $userId = 'user_' . time() . '_' . bin2hex(random_bytes(4));
        $verifyToken = generateToken();

        $newUser = [
            'id' => $userId,
            'username' => $username,
            'email' => $email,
            'whatsapp' => $whatsapp,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'verified' => false,
            'balance' => 0,
            'rating' => 0,
            'total_ratings' => 0,
            'avatar' => "https://ui-avatars.com/api/?name=" . urlencode($username) . "&background=135bec&color=fff",
            'created_at' => date('Y-m-d H:i:s'),
            'session_token' => null
        ];

        $users[] = $newUser;
        saveUsers($users);

        // Save verification token
        $tokens = loadTokens();
        $tokens[$verifyToken] = [
            'user_id' => $userId,
            'email' => $email,
            'created_at' => time(),
            'used' => false
        ];
        saveTokens($tokens);

        // Send verification email
        sendVerificationEmail($email, $username, $verifyToken);

        echo json_encode([
            'success' => true,
            'message' => 'Account created! Please check your email for verification link.',
            'email' => $email
        ]);
        break;

    case 'login':
        $identifier = trim($_POST['identifier'] ?? ''); // email or username
        $password = $_POST['password'] ?? '';

        if (empty($identifier) || empty($password)) {
            echo json_encode(['success' => false, 'error' => 'All fields are required']);
            exit;
        }

        $users = loadUsers();
        $foundUser = null;

        foreach ($users as &$user) {
            if (
                strtolower($user['email']) === strtolower($identifier) ||
                strtolower($user['username']) === strtolower($identifier)
            ) {
                $foundUser = &$user;
                break;
            }
        }

        if (!$foundUser) {
            echo json_encode(['success' => false, 'error' => 'Invalid credentials']);
            exit;
        }

        if (!password_verify($password, $foundUser['password'])) {
            echo json_encode(['success' => false, 'error' => 'Invalid credentials']);
            exit;
        }

        if (!$foundUser['verified']) {
            echo json_encode(['success' => false, 'error' => 'Please verify your email first']);
            exit;
        }

        // Create session token
        $sessionToken = generateToken();
        $foundUser['session_token'] = $sessionToken;
        $foundUser['last_login'] = date('Y-m-d H:i:s');

        saveUsers($users);

        // Return user data (without password)
        $userData = $foundUser;
        unset($userData['password']);

        echo json_encode([
            'success' => true,
            'message' => 'Login successful',
            'user' => $userData,
            'token' => $sessionToken
        ]);
        break;

    case 'verify':
        $token = $_GET['token'] ?? '';

        if (empty($token)) {
            echo json_encode(['success' => false, 'error' => 'Invalid verification link']);
            exit;
        }

        $tokens = loadTokens();

        if (!isset($tokens[$token])) {
            echo json_encode(['success' => false, 'error' => 'Invalid or expired verification link']);
            exit;
        }

        $tokenData = $tokens[$token];

        if ($tokenData['used']) {
            echo json_encode(['success' => false, 'error' => 'This verification link has already been used']);
            exit;
        }

        // Check if token is expired (24 hours)
        if (time() - $tokenData['created_at'] > 86400) {
            echo json_encode(['success' => false, 'error' => 'Verification link has expired']);
            exit;
        }

        // Mark user as verified and create session
        $users = loadUsers();
        foreach ($users as &$user) {
            if ($user['id'] === $tokenData['user_id']) {
                $user['verified'] = true;
                $sessionToken = generateToken();
                $user['session_token'] = $sessionToken;
                $user['verified_at'] = date('Y-m-d H:i:s');

                // Mark token as used
                $tokens[$token]['used'] = true;
                saveTokens($tokens);
                saveUsers($users);

                // Return user data for auto-login
                $userData = $user;
                unset($userData['password']);

                echo json_encode([
                    'success' => true,
                    'message' => 'Email verified successfully!',
                    'user' => $userData,
                    'token' => $sessionToken,
                    'auto_login' => true
                ]);
                exit;
            }
        }

        echo json_encode(['success' => false, 'error' => 'User not found']);
        break;

    case 'check_session':
        $token = $_POST['token'] ?? $_GET['token'] ?? '';

        if (empty($token)) {
            echo json_encode(['success' => false, 'error' => 'No session token']);
            exit;
        }

        $users = loadUsers();
        foreach ($users as $user) {
            if (isset($user['session_token']) && $user['session_token'] === $token) {
                $userData = $user;
                unset($userData['password']);

                echo json_encode([
                    'success' => true,
                    'user' => $userData
                ]);
                exit;
            }
        }

        echo json_encode(['success' => false, 'error' => 'Invalid session']);
        break;

    case 'logout':
        $token = $_POST['token'] ?? '';

        if (!empty($token)) {
            $users = loadUsers();
            foreach ($users as &$user) {
                if (isset($user['session_token']) && $user['session_token'] === $token) {
                    $user['session_token'] = null;
                    saveUsers($users);
                    break;
                }
            }
        }

        echo json_encode(['success' => true, 'message' => 'Logged out successfully']);
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
}
