<?php
// session_fix.php — forces session refresh from DB
require_once __DIR__ . '/includes/config.php';

// If a uid is passed (from register), force that user's session
if (isset($_GET['uid']) && isset($_GET['tok'])) {
    $uid = (int)$_GET['uid'];
    $tok = $_GET['tok'];
    
    // Verify token (simple: hash of uid + secret)
    $secret = 'vetnet_sess_fix_2026';
    $expected = hash('sha256', $uid . $secret);
    
    if (hash_equals($expected, $tok)) {
        // Destroy any existing session
        session_name(SESSION_NAME);
        if (session_status() === PHP_SESSION_NONE) session_start();
        $_SESSION = [];
        session_destroy();
        
        // Delete cookie
        setcookie(SESSION_NAME, '', [
            'expires'  => time() - 3600,
            'path'     => '/',
            'secure'   => isset($_SERVER['HTTPS']),
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
        
        // Start fresh session
        session_start();
        session_regenerate_id(true);
        
        // Load user from DB
        $stmt = db()->prepare(
            "SELECT id, name, phone, email, role, wilaya, lang_pref, theme_pref 
             FROM baitari_users WHERE id = :id AND is_active = 1 LIMIT 1"
        );
        $stmt->execute([':id' => $uid]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            $role = $user['role'] ?? '';
            if (in_array($role, ['pet_owner','farm_owner',''])) $role = 'client';
            
            $_SESSION['user'] = [
                'id'         => (int)$user['id'],
                'name'       => $user['name'],
                'role'       => $role,
                'lang_pref'  => $user['lang_pref']  ?? 'ar',
                'theme_pref' => $user['theme_pref'] ?? 'light',
            ];
            
            // Redirect based on role
            $dest = $role === 'vet' ? 'pages/vet-onboarding.php' : 'index.php';
            header("Location: $dest");
            exit;
        }
    }
}

// If anything failed, go to login
header('Location: login.php');
exit;
