<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Check if already logged in
if (isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'admin') {
    header('Location: admin-dashboard.php');
    exit;
}

$error = '';
$success = '';

// Login form handling
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (!empty($email) && !empty($password)) {
        try {
            $stmt = $pdo->prepare("SELECT u.id, u.email, u.password_hash, u.user_type, u.is_active,
                                  a.first_name, a.last_name, a.profile_photo
                                  FROM users u
                                  JOIN admins a ON u.id = a.id
                                  WHERE u.email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user && password_verify($password, $user['password_hash']) && $user['is_active']) {
                // Set session variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['user_type'] = $user['user_type'];
                $_SESSION['first_name'] = $user['first_name'];
                $_SESSION['last_name'] = $user['last_name'];
                $_SESSION['profile_photo'] = $user['profile_photo'] ?: 'img/profile-placeholder.jpg';
                
                // Update last login
                $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?")->execute([$user['id']]);
                
                // Log login activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, ip_address, user_agent, created_at
                ) VALUES (?, ?, ?, ?, ?, NOW())")->execute([
                    $user['id'],
                    'login',
                    'Admin login successful',
                    $_SERVER['REMOTE_ADDR'],
                    $_SERVER['HTTP_USER_AGENT']
                ]);
                
                // Redirect to dashboard
                header('Location: admin-dashboard.php');
                exit;
            } else {
                $error = "Invalid email or password.";
            }
        } catch (Exception $e) {
            $error = "Login failed. Please try again.";
        }
    } else {
        $error = "Please enter both email and password.";
    }
}

// Password reset request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $email = trim($_POST['email'] ?? '');
    
    if (!empty($email)) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND user_type = 'admin'");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if ($user) {
            // Generate reset token
            $token = bin2hex(random_bytes(32));
            
            // Store in database
            $stmt = $pdo->prepare("INSERT INTO password_resets (email, token, created_at) 
                                  VALUES (?, ?, NOW()) 
                                  ON DUPLICATE KEY UPDATE token = VALUES(token), created_at = NOW()");
            $stmt->execute([$email, $token]);
            
            // In a real application, send email with reset link
            // For now, just show success message
            $success = "Password reset instructions have been sent to your email.";
        } else {
            $error = "No admin account found with that email address.";
        }
    } else {
        $error = "Please enter your email address.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Admin Login - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .login-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.7)), url('img/header-bg.jpg');
            background-size: cover;
        }
        .login-box {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 40px;
            max-width: 450px;
            width: 100%;
            margin: 0 auto;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        .form-tabs {
            border-bottom: 2px solid #eee;
            margin-bottom: 30px;
        }
        .form-tab {
            padding: 15px 0;
            text-align: center;
            cursor: pointer;
            color: #6c757d;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
        }
        .form-tab.active {
            color: #3fb7fe;
            border-bottom-color: #3fb7fe;
            font-weight: 600;
        }
        .form-tab:hover {
            color: #3fb7fe;
        }
        .btn-primary {
            background: #3fb7fe;
            border: none;
            padding: 12px 30px;
            border-radius: 30px;
            font-weight: 600;
        }
        .btn-primary:hover {
            background: #2d9de5;
        }
        .form-footer {
            text-align: center;
            margin-top: 20px;
            color: #6c757d;
        }
        .form-footer a {
            color: #3fb7fe;
            text-decoration: none;
        }
        .form-footer a:hover {
            text-decoration: underline;
        }
        .logo-container {
            text-align: center;
            margin-bottom: 30px;
        }
        .logo-container img {
            height: 80px;
            margin-bottom: 15px;
        }
        .logo-container h3 {
            color: #3fb7fe;
            margin: 0;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-6">
                    <div class="login-box">
                        <div class="logo-container">
                            <img src="img/jhoverseas.jpg" alt="JV Overseas Education" class="mb-3">
                            <h3 class="text-primary">Admin Portal</h3>
                        </div>
                        
                        <!-- Login Form -->
                        <div id="loginForm">
                            <?php if (isset($error)): ?>
                                <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                            <?php endif; ?>
                            
                            <?php if (isset($success)): ?>
                                <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
                            <?php endif; ?>
                            
                            <form method="POST">
                                <div class="form-group">
                                    <label>Email Address</label>
                                    <input type="email" name="email" class="form-control" required>
                                </div>
                                <div class="form-group">
                                    <label>Password</label>
                                    <input type="password" name="password" class="form-control" required>
                                </div>
                                <div class="form-group">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="remember">
                                        <label class="custom-control-label" for="remember">Remember me</label>
                                    </div>
                                </div>
                                <button type="submit" name="login" class="btn btn-primary btn-block">Login</button>
                            </form>
                            
                            <div class="form-footer mt-3">
                                <a href="#" id="showForgot">Forgot Password?</a>
                            </div>
                        </div>
                        
                        <!-- Forgot Password Form -->
                        <div id="forgotForm" style="display: none;">
                            <h5 class="text-center mb-4">Reset Password</h5>
                            <p class="text-center text-muted mb-4">Enter your email address and we'll send you instructions to reset your password.</p>
                            
                            <form method="POST">
                                <div class="form-group">
                                    <label>Email Address</label>
                                    <input type="email" name="email" class="form-control" required>
                                </div>
                                <button type="submit" name="reset_password" class="btn btn-primary btn-block">Send Reset Instructions</button>
                            </form>
                            
                            <div class="form-footer mt-3">
                                <a href="#" id="showLogin">Back to Login</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        // Toggle between login and forgot password forms
        $('#showForgot').on('click', function(e) {
            e.preventDefault();
            $('#loginForm').hide();
            $('#forgotForm').show();
        });
        
        $('#showLogin').on('click', function(e) {
            e.preventDefault();
            $('#forgotForm').hide();
            $('#loginForm').show();
        });
    </script>
</body>
</html>