<?php
// ============================================================
//  MediCore — Customer Portal Session & Auth Helpers
//  File: includes/customer_auth.php
//  Mirrors includes/auth.php's shape (require_login-style guard,
//  is_ajax_request, base_url) but for the public phone/OTP portal.
//  Uses the SAME PHP session (same cookie) as staff auth but under
//  distinct $_SESSION keys ('customer_*' vs 'user_*'), so a staff
//  member and a logged-in customer can coexist in one browser
//  without either session clobbering the other.
// ============================================================

if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_samesite' => 'Lax',
        'cookie_path'      => '/',
    ]);
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/customer_portal.php';
require_once __DIR__ . '/gateways.php';
ensure_customer_portal_schema();

if (!function_exists('base_url')) {
    function base_url(string $path = ''): string {
        $base = defined('APP_BASE') ? APP_BASE : '';
        return $base . '/' . ltrim($path, '/');
    }
}

function customer_is_ajax_request(): bool {
    return (
        (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
            && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
        || (!empty($_SERVER['CONTENT_TYPE'])
            && stripos($_SERVER['CONTENT_TYPE'], 'application/json') !== false)
        || strpos($_SERVER['SCRIPT_NAME'] ?? '', '/api/') !== false
    );
}

// ── Require a logged-in, OTP-verified customer ──────────────────
function require_customer_login(): void {
    if (empty($_SESSION['customer_id'])) {
        if (customer_is_ajax_request()) {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode([
                'success'        => false,
                'error'          => 'Please log in to continue.',
                'session_expired'=> true,
            ]);
            exit;
        }
        header('Location: ' . base_url('shop/login.php'));
        exit;
    }
}

// ── Current customer helpers ──────────────────────────────────
function current_customer_id(): int       { return (int)($_SESSION['customer_id']    ?? 0); }
function current_customer_name(): string  { return $_SESSION['customer_name']  ?? ''; }
function current_customer_phone(): string { return $_SESSION['customer_phone'] ?? ''; }
function customer_logged_in(): bool       { return !empty($_SESSION['customer_id']); }

// ── Start a customer session after OTP verification succeeds ────
function customer_login_session(array $customer): void {
    session_regenerate_id(true);
    $_SESSION['customer_id']    = (int)$customer['id'];
    $_SESSION['customer_name']  = $customer['name'];
    $_SESSION['customer_phone'] = $customer['phone'];
}

function customer_logout(): void {
    unset($_SESSION['customer_id'], $_SESSION['customer_name'], $_SESSION['customer_phone']);
    header('Location: ' . base_url('shop/login.php'));
    exit;
}
