<?php
session_start();
require_once '../includes/config.php'; // Database connection

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $identifier = trim($_POST['identifier']); // Username or email
    $password = $_POST['password'];

    // Validate input
    if (empty($identifier) || empty($password)) {
        header('Location: ../login.php?error=All fields are required.');
        exit;
    }

    try {
        // Prepare SQL query to fetch user by username or email
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :identifier OR email = :identifier");
        $stmt->execute(['identifier' => $identifier]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // Verify password
        if ($user && password_verify($password, $user['password'])) {
            // Start session and store user data
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];

            // Redirect based on role
            switch ($user['role']) {
                case 'admin':
                    header('Location: ../admin/dashboard.php'); // Redirect to admin folder
                    break;
                case 'officer':
                    header('Location: ../officer/dashboard.php'); // Redirect to officer folder
                    break;
                default:
                    // Handle unknown roles
                    header('Location: ../login.php?error=unknown_role');
                    exit;
            }
            exit;
        } else {
            // Invalid credentials
            header('Location: ../login.php?error=Invalid username/email or password.');
            exit;
        }
    } catch (PDOException $e) {
        error_log($e->getMessage());
        header('Location: ../login.php?error=Database error. Please try again.');
        exit;
    }
} else {
    // Redirect if accessed directly
    header('Location: ../login.php');
    exit;
}