<?php
declare(strict_types=1);
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/referrals.php';

function find_user_by_email(PDO $pdo, string $email) {
    $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    return $stmt->fetch();
}

function attempt_login(PDO $pdo, string $email, string $password): bool {
    $user = find_user_by_email($pdo, $email);
    if (!$user) {
        return false;
    }
    if ($user['status'] !== 'active') {
        return false;
    }
    if (!password_verify($password, $user['password'])) {
        return false;
    }
    start_session();
    $_SESSION['user'] = [
        'id' => (int)$user['id'],
        'full_name' => $user['full_name'],
        'email' => $user['email'],
        'role' => $user['role']
    ];
    return true;
}

function logout(): void {
    start_session();
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
    }
    session_destroy();
}

function register_customer(PDO $pdo, string $full_name, string $email, string $phone, string $password): array {
    $errors = [];
    if (!valid_email($email)) {
        $errors[] = 'Invalid email';
    }
    if (strlen($password) < 6) {
        $errors[] = 'Password too short';
    }
    if (!empty($errors)) {
        return $errors;
    }
    $exists = find_user_by_email($pdo, $email);
    if ($exists) {
        return ['Email already registered'];
    }

    require_once __DIR__ . '/settings.php';
    $verifyEnabled = get_setting($pdo, 'email_verification_enabled', false);
    $status = $verifyEnabled ? 'inactive' : 'active';

    $stmt = $pdo->prepare('INSERT INTO users (full_name,email,phone,password,role,status,created_at) VALUES (?,?,?,?,?,?,?)');
    $stmt->execute([
        $full_name,
        $email,
        $phone,
        password_hash($password, PASSWORD_DEFAULT),
        'customer',
        $status,
        date('c')
    ]);
    $uid = (int)$pdo->lastInsertId();
    // assign referral code
    ensure_user_ref_code($pdo, $uid);
    // link referrer if cookie present and valid
    assign_referrer_on_registration($pdo, $uid, $email);
    // queue verification email
    if ($verifyEnabled && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        require_once __DIR__ . '/notifications.php';
        send_verification_email($pdo, $uid, $email, $full_name);
    }
    return [];
}
