<?php
// auth/login.php
ob_start();
session_start(); // Ensure session is started
$projectRoot = dirname(__DIR__); 
require_once $projectRoot . '/config/database.php'; 
require_once $projectRoot . '/config/config.php';   
require_once $projectRoot . '/includes/functions.php'; 
ob_end_clean(); 

try {
    $stmtSet = $pdo->query("SELECT school_name, logo FROM system_settings LIMIT 1");
    $settings = $stmtSet->fetch(PDO::FETCH_ASSOC);
    
    if ($settings) {
        $display_name = !empty($settings['school_name']) ? $settings['school_name'] : $school_name;
        if (!empty($settings['logo']) && file_exists("../assets/img/" . $settings['logo'])) {
            $school_logo = "../assets/img/" . $settings['logo'];
        } else {
            $school_logo = "../assets/img/logo.png";
        }
    } else {
        $display_name = $school_name;
        $school_logo = "../assets/img/logo.png";
    }
} catch (PDOException $e) {
    $display_name = "Portal Login";
    $school_logo = "../assets/img/logo.png";
}

// Check if user is already logged in
if (isset($_SESSION['role'])) {
    if ($_SESSION['role'] == 'admin' || $_SESSION['role'] == 'subadmin') header("Location: ../admin/dashboard.php");
    elseif ($_SESSION['role'] == 'teacher') header("Location: ../teacher/dashboard.php");
    else header("Location: ../student/dashboard.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 'clean' is from your functions.php
    $identifier = clean($_POST['identifier']);
    $password = $_POST['password'];
    $role_type = $_POST['role_type']; 

    if ($role_type == 'staff') {
        // UPDATED: Search by 'username' instead of 'email'
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$identifier]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id']; 
            $_SESSION['role'] = $user['role']; 
            $_SESSION['name'] = $user['fullname'];
            $_SESSION['username'] = $user['username'];

            // Admins and Sub-Admins go to the same dashboard
            if ($user['role'] == 'admin' || $user['role'] == 'subadmin') {
                header("Location: ../admin/dashboard.php");
            } else {
                header("Location: ../teacher/dashboard.php");
            }
            exit(); 
        } else {
            $error = "Invalid Staff Credentials.";
        }
    } else {
        // Student login remains the same
        $stmt = $pdo->prepare("SELECT * FROM students WHERE reg_number = ?");
        $stmt->execute([$identifier]);
        $student = $stmt->fetch();

        if ($student && password_verify($password, $student['password'])) {
            $_SESSION['user_id'] = $student['id']; 
            $_SESSION['role'] = 'student';
            $_SESSION['name'] = $student['fullname'];
            header("Location: ../student/dashboard.php");
            exit();
        } else {
            $error = "Invalid Student Credentials.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | <?php echo htmlspecialchars($display_name); ?></title>
    <style>
        :root {
            --primary-color: #3498db;
            --dark-color: #2c3e50;
            --bg-color: #f0f2f5;
        }

        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            min-height: 100vh; 
            background: var(--bg-color); 
            margin: 0; 
            padding: 20px; 
            box-sizing: border-box;
        }

        .login-container { 
            background: #fff; 
            padding: 40px 30px; 
            border-radius: 15px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.1); 
            width: 100%; 
            max-width: 420px; 
            text-align: center; 
            box-sizing: border-box;
        }

        .school-logo { 
            width: 100px; 
            height: 100px; 
            object-fit: contain; 
            margin-bottom: 15px; 
        }

        h2 { 
            color: var(--dark-color); 
            margin-bottom: 25px; 
            font-size: 1.2rem; 
            text-transform: uppercase; 
            letter-spacing: 1px;
            position: relative;
            padding-bottom: 10px;
        }

        h2::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 50px;
            height: 3px;
            background: var(--primary-color);
        }

        .form-group {
            text-align: left;
            margin-bottom: 15px;
        }

        label { 
            font-weight: 600; 
            color: #555; 
            font-size: 14px; 
            display: block; 
            margin-bottom: 8px; 
        }

        input, select, button { 
            width: 100%; 
            padding: 12px 15px; 
            border: 1px solid #ddd; 
            border-radius: 8px; 
            box-sizing: border-box; 
            font-size: 16px; 
            transition: all 0.3s ease;
        }

        input:focus, select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        button { 
            background: var(--primary-color); 
            color: white; 
            border: none; 
            cursor: pointer; 
            font-weight: bold; 
            margin-top: 15px; 
            text-transform: uppercase;
        }

        button:hover { 
            background: #2980b9; 
            transform: translateY(-1px);
        }

        .error { 
            color: #721c24; 
            background: #f8d7da; 
            padding: 12px; 
            border-radius: 8px; 
            font-size: 14px; 
            margin-bottom: 20px; 
            border: 1px solid #f5c6cb;
        }

        .signature {
            margin-top: 30px;
            font-size: 12px;
            color: #7f8c8d;
            border-top: 1px solid #eee;
            padding-top: 15px;
        }

        .signature a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: bold;
        }

        @media (max-width: 480px) {
            .login-container { padding: 30px 20px; }
            h2 { font-size: 1rem; }
        }
    </style>
</head>
<body>

<div class="login-container">
    <img src="<?php echo $school_logo; ?>?v=<?php echo (file_exists($school_logo)) ? filemtime($school_logo) : time(); ?>" 
         class="school-logo" 
         alt="School Logo" 
         onerror="this.src='../assets/img/logo.png'">
    
    <h2><?php echo htmlspecialchars($display_name); ?></h2>
    
    <?php if(isset($error)) echo "<div class='error'>$error</div>"; ?>
    
    <form method="POST">
        <div class="form-group">
            <label>Login As:</label>
            <select name="role_type" id="role_type" onchange="updatePlaceholder()">
                <option value="staff">Staff (Admin/Teacher)</option>
                <option value="student">Student</option>
            </select>
        </div>

        <div class="form-group">
            <label id="id_label">Username</label>
            <input type="text" name="identifier" id="identifier" placeholder="Enter your username" required>
        </div>
        
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="password" placeholder="••••••••" required>
        </div>
        
        <button type="submit">Login to Portal</button>
    </form>

    <div class="signature">
        ignited by <a href="#" target="_blank">The 1800 Hub</a>
    </div>
</div>

<script>
    function updatePlaceholder() {
        var role = document.getElementById('role_type').value;
        var input = document.getElementById('identifier');
        var label = document.getElementById('id_label');
        if (role === 'staff') {
            label.innerText = "Username";
            input.placeholder = "Enter your username";
        } else {
            label.innerText = "Registration Number";
            input.placeholder = "Enter Reg Number";
        }
    }
</script>
</body>
</html>