<?php
session_start();
include '../includes/db.php';

$error = "";
$flash_success = "";

// Flash message from reset_password.php
if (!empty($_SESSION['flash_success'])) {
    $flash_success = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // CSRF validation
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $error = "Invalid request. Please try again.";
    } else {
        $user_id = trim($_POST['username']);
        $password = trim($_POST['password']);

        if (empty($user_id) || empty($password)) {
            $error = "Please enter your User ID and Password.";
        } else {
            // Prepared statement to prevent SQL Injection
            $stmt = $conn->prepare("SELECT id, password FROM admin_users WHERE username = ?");
            $stmt->bind_param("s", $user_id);
            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                $stmt->bind_result($id, $hashed_password);
                $stmt->fetch();

                if (password_verify($password, $hashed_password)) {
                    // Regenerate session ID on successful login
                    session_regenerate_id(true);
                    $_SESSION['admin_id'] = $id;
                    $_SESSION['admin_logged_in'] = true;
                    // Regenerate CSRF token after login
                    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                    header("Location: dashboard.php");
                    exit;
                } else {
                    $error = "Invalid password. Please try again.";
                }
            } else {
                $error = "Invalid User ID. Please try again.";
            }
            $stmt->close();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
   
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login – Balimeen Pvt Ltd</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        body { background-color: #f4f7f6; display: flex; align-items: center; justify-content: center; height: 100vh; }
        .login-card { width: 100%; max-width: 400px; padding: 2rem; border-radius: 30px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); background: deepskyblue; }
        .password-wrapper { position: relative; }
        .password-wrapper .toggle-eye {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #555;
            background: none;
            border: none;
            padding: 0;
            line-height: 1;
        }
        .password-wrapper input { padding-right: 40px; }
        .forgot-link {
            font-size: 13px;
            color: #fff;
            text-decoration: underline;
            float: right;
            margin-top: 4px;
        }
        .forgot-link:hover { color: #f0f0f0; }
        .email-info {
            font-size: 12px;
            color: #fff;
            text-align: center;
            margin-top: 10px;
        }
    </style>
</head>
<body>
     
    <div class="login-card">
        <h3 class="text-center mb-4">Admin Login</h3>
        <?php if($flash_success): ?>
            <div class="alert alert-success"><?php echo $flash_success; ?></div>
        <?php endif; ?>
        <?php if($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <form method="POST" action="" autocomplete="off">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
            
            <div class="mb-3">
                <label for="username" class="form-label">User ID</label>
                <input type="text" class="form-control" id="username" name="username"
                       value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                       required autocomplete="off">
            </div>
            
            <div class="mb-1">
                <label for="password" class="form-label">Password</label>
                <div class="password-wrapper">
                    <input type="password" class="form-control" id="password" name="password" required autocomplete="current-password">
                    <button type="button" class="toggle-eye" id="togglePassword" aria-label="Toggle password visibility">
                        <i class="fa fa-eye" id="eyeIcon"></i>
                    </button>
                </div>
            </div>
            
            <div class="mb-3">
                <a href="forgot_password.php" class="forgot-link">Forgot Password?</a>
                <div style="clear:both;"></div>
            </div>
            
            <button type="submit" class="btn btn-primary w-100">Login Now</button>
        </form>
        <div class="mt-3 text-center">
            <a href="../index.php" style="color:#fff;">Back to Home</a>
        </div>
        <div class="email-info">
            <i class="fa fa-envelope me-1"></i>balimeenpvtltd@gmail.com
        </div>
    </div>

    <script>
        document.getElementById('togglePassword').addEventListener('click', function() {
            var pwdField = document.getElementById('password');
            var eyeIcon = document.getElementById('eyeIcon');
            if (pwdField.type === 'password') {
                pwdField.type = 'text';
                eyeIcon.classList.remove('fa-eye');
                eyeIcon.classList.add('fa-eye-slash');
            } else {
                pwdField.type = 'password';
                eyeIcon.classList.remove('fa-eye-slash');
                eyeIcon.classList.add('fa-eye');
            }
        });
    </script>
</body>
</html>
