<?php
require_once 'config.php';

if (isLoggedIn()) {
    redirect('index.php');
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $user_type = $_POST['user_type'] ?? 'representative';
    
    if (empty($username) || empty($password)) {
        $error = 'لطفاً نام کاربری و رمز عبور را وارد کنید';
    } else {
        if ($user_type === 'admin') {
            $stmt = $pdo->prepare("SELECT * FROM admins WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();
            
            if ($user) {
                $password_verified = false;
                // 1. Try the new, secure verification method first
                if (password_verify($password, $user['password'])) {
                    $password_verified = true;
                    // Optional: Check if the hash needs to be updated to a newer algorithm
                    if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
                        $new_hash = password_hash($password, PASSWORD_DEFAULT);
                        $pdo->prepare("UPDATE admins SET password = ? WHERE id = ?")->execute([$new_hash, $user['id']]);
                    }
                } 
                // 2. If the new method fails, try the old, insecure method as a fallback
                elseif (function_exists('verifyPassword') && verifyPassword($password, $user['password'])) {
                    $password_verified = true;
                    // 3. IMPORTANT: If the old method works, immediately upgrade the password hash to the new secure one
                    $new_hash = password_hash($password, PASSWORD_DEFAULT);
                    $pdo->prepare("UPDATE admins SET password = ? WHERE id = ?")->execute([$new_hash, $user['id']]);
                }

                if ($password_verified) {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_type'] = 'admin';
                    $_SESSION['username'] = $user['username'];
                    redirect('admin/dashboard.php');
                } else {
                    $error = 'نام کاربری یا رمز عبور اشتباه است';
                }
            } else {
                $error = 'نام کاربری یا رمز عبور اشتباه است';
            }
        } else {
            $stmt = $pdo->prepare("SELECT r.*, p.url as panel_url, p.username as panel_username, p.password as panel_password 
                                   FROM representatives r 
                                   JOIN panels p ON r.panel_id = p.id 
                                   WHERE r.username = ? AND r.status = 'active'");
            $stmt->execute([$username]);
            $user = $stmt->fetch();
            
            if ($user) {
                $password_verified = false;
                // 1. Try the new, secure verification method first
                if (password_verify($password, $user['password'])) {
                    $password_verified = true;
                    // Optional: Check if the hash needs to be updated to a newer algorithm
                    if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
                        $new_hash = password_hash($password, PASSWORD_DEFAULT);
                        $pdo->prepare("UPDATE representatives SET password = ? WHERE id = ?")->execute([$new_hash, $user['id']]);
                    }
                } 
                // 2. If the new method fails, try the old, insecure method as a fallback
                elseif (function_exists('verifyPassword') && verifyPassword($password, $user['password'])) {
                    $password_verified = true;
                    // 3. IMPORTANT: If the old method works, immediately upgrade the password hash to the new secure one
                    $new_hash = password_hash($password, PASSWORD_DEFAULT);
                    $pdo->prepare("UPDATE representatives SET password = ? WHERE id = ?")->execute([$new_hash, $user['id']]);
                }

                if ($password_verified) {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_type'] = 'representative';
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['panel_id'] = $user['panel_id'];
                    redirect('representative/dashboard.php');
                } else {
                    $error = 'نام کاربری یا رمز عبور اشتباه است';
                }
            } else {
                $error = 'نام کاربری یا رمز عبور اشتباه است';
            }
        }
    }
}

$msg = getMessage();
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ورود به سیستم</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700&display=swap" rel="stylesheet">
    <?php
    $theme_path = ROOT_PATH . '/assets/css/theme-dark.css';
    $theme_ver = file_exists($theme_path) ? filemtime($theme_path) : '1';
    ?>
    <link href="assets/css/theme.css?v=<?= $theme_ver ?>" rel="stylesheet">
    <style>
        body { 
            background: radial-gradient(circle at top right, #1e293b, #0f172a);
            min-height: 100vh; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            padding: 1rem; 
            font-family: 'Vazirmatn', sans-serif;
        }
        .login-wrap {
            width: 100%;
            max-width: 440px;
        }
        .login-card {
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(15px);
            border: 1px solid rgba(255,255,255,0.05);
            border-radius: 28px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            padding: 3rem;
            position: relative;
            overflow: hidden;
        }
        .login-card::before {
            content: '';
            position: absolute;
            top: -50px;
            right: -50px;
            width: 150px;
            height: 150px;
            background: radial-gradient(circle, rgba(16, 185, 129, 0.1) 0%, transparent 70%);
            z-index: 0;
        }
        .login-card h2 {
            font-size: 1.8rem;
            font-weight: 800;
            margin-bottom: 2rem;
            color: #fff;
            text-align: center;
            position: relative;
            z-index: 1;
        }
        .login-card h2 i { 
            color: var(--accent-primary); 
            margin-left: 0.75rem;
            filter: drop-shadow(0 0 8px rgba(16, 185, 129, 0.4));
        }
        .form-label { 
            color: var(--text-muted); 
            font-size: 0.85rem; 
            font-weight: 500;
            margin-bottom: 0.5rem;
        }
        .form-control-pro {
            background: rgba(255,255,255,0.03) !important;
            border: 1px solid rgba(255,255,255,0.1) !important;
            color: white !important;
            border-radius: 14px;
            padding: 12px 18px;
            transition: all 0.3s;
        }
        .form-control-pro:focus {
            background: rgba(255,255,255,0.05) !important;
            border-color: var(--accent-primary) !important;
            box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.1) !important;
        }
        .btn-login-pro {
            background: linear-gradient(135deg, var(--accent-primary), #059669);
            border: none;
            width: 100%;
            padding: 14px;
            font-weight: 700;
            border-radius: 14px;
            color: #fff;
            margin-top: 1.5rem;
            box-shadow: 0 10px 15px -3px rgba(16, 185, 129, 0.3);
            transition: all 0.3s;
        }
        .btn-login-pro:hover {
            transform: translateY(-2px);
            box-shadow: 0 20px 25px -5px rgba(16, 185, 129, 0.4);
            filter: brightness(1.1);
        }
        .alert { 
            border-radius: 14px; 
            border: none; 
            background: rgba(244, 63, 94, 0.1); 
            color: #fb7185;
            font-size: 0.9rem;
            margin-bottom: 2rem;
        }
        .alert-success {
            background: rgba(16, 185, 129, 0.1);
            color: #34d399;
        }
        .brand-logo {
            width: 64px;
            height: 64px;
            background: rgba(16, 185, 129, 0.1);
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1.5rem;
            color: var(--accent-primary);
            font-size: 2rem;
            border: 1px solid rgba(16, 185, 129, 0.2);
        }
    </style>
</head>
<body>
    <div class="login-wrap">
        <div class="login-card">
            <div class="brand-logo">
                <i class="bi bi-shield-lock-fill"></i>
            </div>
            <h2>ورود به پنل کاربری</h2>
            
            <?php if ($error): ?>
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-circle me-2"></i><?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            
            <?php if ($msg): ?>
                <div class="alert alert-<?= $msg['type'] === 'success' ? 'success' : 'danger' ?>">
                    <i class="bi bi-<?= $msg['type'] === 'success' ? 'check-circle' : 'exclamation-circle' ?> me-2"></i>
                    <?= htmlspecialchars($msg['message']) ?>
                </div>
            <?php endif; ?>
            
            <form method="POST">
                <div class="mb-3">
                    <label class="form-label">نوع دسترسی</label>
                    <select name="user_type" class="form-control form-control-pro" required>
                        <option value="representative" selected>نماینده فروش</option>
                        <option value="admin">مدیر سیستم</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">نام کاربری</label>
                    <input type="text" name="username" class="form-control form-control-pro" required autofocus placeholder="Username">
                </div>
                <div class="mb-4">
                    <label class="form-label">رمز عبور</label>
                    <input type="password" name="password" class="form-control form-control-pro" required placeholder="Password">
                </div>
                <button type="submit" class="btn btn-login-pro">ورود به حساب</button>
            </form>
            
            <div class="mt-5 text-center">
                <p class="text-white-50 small mb-0">طراحی شده برای امنیت و سرعت</p>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
