<?php
ob_start();
require_once __DIR__ . '/../includes/config.php';


function make_sess_token(int $uid): string {
    return hash('sha256', $uid . 'vetnet_sess_fix_2026');
}
function sess_fix_url(int $uid, bool $vet = false): string {
    $tok = make_sess_token($uid);
    $base = 'session_fix.php?uid=' . $uid . '&tok=' . $tok;
    return $vet ? $base . '&vet=1' : $base;
}
session_start_secure();
header('Content-Type: application/json; charset=utf-8');

$action = sanitize_str($_POST['action'] ?? $_GET['action'] ?? '');

// Router - PHP 7/8 compatible
$handlers = [
    'login' => 'handle_login',
    'register' => 'handle_register',
    'logout' => 'handle_logout',
];

if (isset($handlers[$action])) {
    call_user_func($handlers[$action]);
} else {
    json_response(['error' => 'Unknown action: ' . $action], 400);
}

function handle_login(): void {
    $phone = sanitize_str($_POST['phone'] ?? '');
    $pass  = $_POST['password'] ?? '';

    if (strlen($phone) !== 10 || !$pass) {
        json_response(['error' => 'بيانات غير صحيحة'], 422);
    }

    $stmt = db()->prepare(
        "SELECT id, name, role, password_hash, lang_pref, theme_pref, is_active
         FROM baitari_users WHERE phone = :phone LIMIT 1"
    );
    $stmt->execute([':phone' => $phone]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($pass, $user['password_hash'])) {
        json_response(['error' => 'رقم الهاتف أو كلمة المرور غير صحيحة'], 401);
    }
    // Normalize role
    $userRole = $user['role'] ?? '';
    if (in_array($userRole, ['pet_owner','farm_owner',''])) $userRole = 'client';
    $user['role'] = $userRole;

    if (!$user['is_active']) {
        json_response(['error' => 'الحساب موقوف. تواصل مع الدعم'], 403);
    }

    // Properly destroy old session and cookie
    $_SESSION = [];
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_unset();
        session_destroy();
        // Delete the session cookie
        if (isset($_COOKIE[SESSION_NAME])) {
            setcookie(SESSION_NAME, '', [
                'expires'  => time() - 3600,
                'path'     => '/',
                'secure'   => true,
                'httponly' => true,
                'samesite' => 'Lax',
            ]);
        }
    }
    // Start completely new session
    session_name(SESSION_NAME);
    session_start();
    session_regenerate_id(true);

    // Set session with normalized role
    $_SESSION['user'] = [
        'id'         => (int)$user['id'],
        'name'       => $user['name'],
        'role'       => $user['role'], // already normalized above
        'lang_pref'  => $user['lang_pref']  ?? 'ar',
        'theme_pref' => $user['theme_pref'] ?? 'light',
    ];

    // Update last_login
    db()->prepare("UPDATE baitari_users SET last_login=NOW() WHERE id=:id")
       ->execute([':id' => $user['id']]);

    $fixUrl = sess_fix_url((int)$user['id']);
    json_response([
        'success'  => true,
        'role'     => $user['role'],
        'redirect' => $fixUrl,
    ]);
}

function handle_register(): void {
    $name  = sanitize_str($_POST['name']  ?? '');
    $phone = sanitize_str($_POST['phone'] ?? '');
    $email = sanitize_str($_POST['email'] ?? '');
    $pass  = $_POST['password'] ?? '';
    $role  = sanitize_str($_POST['role']  ?? 'client');
    $wilaya= sanitize_str($_POST['wilaya']?? '');

    if (!$name || strlen($phone) !== 10 || strlen($pass) < 8) {
        json_response(['error' => 'بيانات غير مكتملة'], 422);
    }

    // Check phone uniqueness
    $exists = db()->prepare("SELECT id FROM baitari_users WHERE phone=:p LIMIT 1");
    $exists->execute([':p' => $phone]);
    if ($exists->fetch()) {
        json_response(['error' => 'رقم الهاتف مسجّل بالفعل'], 409);
    }

    $hash = password_hash($pass, PASSWORD_BCRYPT, ['cost' => 12]);
    $stmt = db()->prepare(
        "INSERT INTO baitari_users (name, phone, email, password_hash, role, wilaya, is_active)
         VALUES (:name, :phone, :email, :hash, :role, :wilaya, 1)"
    );
    $stmt->execute([
        ':name'   => $name,
        ':phone'  => $phone,
        ':email'  => $email ?: null,
        ':hash'   => $hash,
        ':role'   => in_array($role, ['client','vet','admin']) ? $role : 'client',
        ':wilaya' => $wilaya ?: null,
    ]);
    $uid = db()->lastInsertId();

    // If vet, create pending profile
    if ($role === 'vet') {
        try {
            db()->prepare(
                "INSERT INTO baitari_vet_profiles
                  (vet_id, license_no, is_verified, verification_status)
                  VALUES (:vid, :lic, 0, 'pending_docs')"
            )->execute([
                ':vid' => $uid,
                ':lic' => sanitize_str($_POST['license'] ?? 'PENDING'),
            ]);
        } catch (\Exception $e) {
            // Fallback: without verification_status column (old schema)
            try {
                db()->prepare(
                    "INSERT INTO baitari_vet_profiles (vet_id, license_no, is_verified)
                      VALUES (:vid, :lic, 0)"
                )->execute([':vid' => $uid, ':lic' => sanitize_str($_POST['license'] ?? 'PENDING')]);
            } catch (\Exception $e2) {}
        }
        // Destroy old session properly
        $_SESSION = [];
        if (session_status() === PHP_SESSION_ACTIVE) {
            session_unset();
            session_destroy();
            if (isset($_COOKIE[SESSION_NAME])) {
                setcookie(SESSION_NAME, '', ['expires'=>time()-3600,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']);
            }
        }
        session_name(SESSION_NAME);
        session_start();
        session_regenerate_id(true);

        $_SESSION['user'] = [
            'id'         => (int)$uid,
            'name'       => $name,
            'role'       => 'vet',
            'lang_pref'  => 'ar',
            'theme_pref' => 'light',
        ];
        $fixUrl = sess_fix_url((int)$uid, true);
        json_response(['success' => true, 'pending' => true, 'redirect' => $fixUrl]);
    }

    // Destroy old session properly
    $_SESSION = [];
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_unset();
        session_destroy();
        if (isset($_COOKIE[SESSION_NAME])) {
            setcookie(SESSION_NAME, '', ['expires'=>time()-3600,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']);
        }
    }
    session_name(SESSION_NAME);
    session_start();
    session_regenerate_id(true);

    // Auto-login new user
    $_SESSION['user'] = [
        'id'         => (int)$uid,
        'name'       => $name,
        'role'       => $role,
        'lang_pref'  => 'ar',
        'theme_pref' => 'light',
    ];
    $fixUrl = sess_fix_url((int)$uid);
    json_response(['success' => true, 'role' => $role, 'redirect' => $fixUrl]);
}

function handle_logout(): void {
    // Session already started at top of file
    $_SESSION = [];
    session_destroy();
    json_response(['success' => true, 'redirect' => 'login.php']);
}
