<?php
// Include database configuration
include('config/database.php');
session_start();

// Initialize variables
$username = $password = $role = '';
$errors = [];

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $role = $_POST['role'];

    // Validate input
    if (empty($username)) $errors[] = "Username is required";
    if (empty($password)) $errors[] = "Password is required";
    if (empty($role)) $errors[] = "Please select a role";

    // Check for errors
    if (count($errors) == 0) {
        // Determine which table to query based on role
        $table = ($role == 'admin') ? 'admin' : 'assessors';
        
        // Fetch user from the database
        $sql = "SELECT * FROM $table WHERE username = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows == 1) {
                $row = $result->fetch_assoc();
                // Verify password
                if (password_verify($password, $row['password'])) {
                    // Store user information in session based on role
                    if ($role == 'admin') {
                        $_SESSION['admin_id'] = $row['id'];
                        $_SESSION['admin_username'] = $row['username'];
                        header("Location: admin/public/assign.php");
                    } else {
                        $_SESSION['assessor_id'] = $row['id'];
                        $_SESSION['assessor_name'] = $row['name'];
                        header("Location: assessors/index.php");
                    }
                    exit();
                } else {
                    $errors[] = "Invalid password.";
                }
            } else {
                $errors[] = "Invalid username for selected role.";
            }
            $stmt->close();
        } else {
            $errors[] = "Database error: Unable to prepare statement.";
        }
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Business Pitch Challenger</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="assets/css/main.css?v=1.1">
    <link rel="stylesheet" href="assets/css/components.css?v=1.1">
    <style>
        body {
            background-image: url('assets/images/hero/1.JPG');
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            position: relative;
        }
        
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: -1;
        }
        
        .login-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }
        
        .login-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 0;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            max-width: 380px;
            width: 100%;
            padding: 1rem;
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .login-header img {
            height: 40px;
            width: auto;
            margin-bottom: 0.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }
        
        .login-title {
            color: #333;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .login-subtitle {
            color: #666;
            font-size: 0.9rem;
        }
        
        .form-control {
            border-radius: 0;
            border: 1px solid #ddd;
            padding: 8px 12px;
            font-size: 0.95rem;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-login {
            background: linear-gradient(45deg, #2c2b7c, #764ba2);
            border: none;
            border-radius: 0;
            padding: 8px 25px;
            font-weight: 600;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .back-link {
            text-align: center;
            margin-top: 0.75rem;
        }
        
        .back-link a {
            color: #2c2b7c;
            text-decoration: none;
            font-weight: 500;
        }
        
        .back-link a:hover {
            text-decoration: underline;
        }
        
        .role-selector {
            margin-bottom: 1rem;
        }
        
        .role-option {
            border: 2px solid #ddd;
            border-radius: 8px;
            padding: 0.5rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }
        
        .role-option:hover {
            border-color: #2c2b7c;
            background: #f8f9ff;
        }
        
        .role-option.selected {
            border-color: #2c2b7c;
            background: #f8f9ff;
        }
        
        .role-option input[type="radio"] {
            margin-right: 10px;
        }
        
        .role-icon {
            font-size: 1.2rem;
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <img src="assets/images/logos/logo.png" alt="UEW iHub Logo">
                <h2 class="login-title">Welcome Back</h2>
                <p class="login-subtitle">Business Pitch Challenger 2025/2026 - 2nd Edition</p>
            </div>

            <?php if (!empty($errors)) : ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php foreach ($errors as $error) : ?>
                        <div><?php echo htmlspecialchars($error); ?></div>
                    <?php endforeach; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <form method="POST" action="login.php">
                <div class="role-selector">
                    <label class="form-label fw-bold">Select Your Role:</label>
                    <div class="role-option" onclick="selectRole('admin')">
                        <input type="radio" name="role" value="admin" id="role-admin" <?php echo ($role == 'admin') ? 'checked' : ''; ?>>
                        <label for="role-admin" class="mb-0">
                            <i class="fas fa-user-shield role-icon text-primary"></i>
                            <strong>Admin</strong> - Manage proposals and assign assessors
                        </label>
                    </div>
                    <div class="role-option" onclick="selectRole('assessor')">
                        <input type="radio" name="role" value="assessor" id="role-assessor" <?php echo ($role == 'assessor') ? 'checked' : ''; ?>>
                        <label for="role-assessor" class="mb-0">
                            <i class="fas fa-clipboard-check role-icon text-success"></i>
                            <strong>Assessor</strong> - Evaluate and score proposals
                        </label>
                    </div>
                </div>

                <div class="mb-3">
                    <label for="username" class="form-label">Username</label>
                    <input type="text" class="form-control" id="username" name="username" 
                           value="<?php echo htmlspecialchars($username); ?>" required>
                </div>
                
                <div class="mb-4">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" class="form-control" id="password" name="password" required>
                </div>
                
                <button type="submit" class="btn btn-primary btn-login">
                    <i class="fas fa-sign-in-alt me-2"></i>Login
                </button>
            </form>

            <div class="back-link">
                <a href="index.php">
                    <i class="fas fa-arrow-left me-1"></i>Back to Home
                </a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function selectRole(role) {
            // Remove selected class from all options
            document.querySelectorAll('.role-option').forEach(option => {
                option.classList.remove('selected');
            });
            
            // Add selected class to clicked option
            event.currentTarget.classList.add('selected');
            
            // Check the radio button
            document.getElementById('role-' + role).checked = true;
        }
        
        // Initialize selected role styling
        document.addEventListener('DOMContentLoaded', function() {
            const selectedRole = document.querySelector('input[name="role"]:checked');
            if (selectedRole) {
                selectedRole.closest('.role-option').classList.add('selected');
            }
        });
    </script>
</body>
</html>
