<?php
// db.php

$host = '204.11.58.166';
$port = '3306';
$dbname = 'service_portal';
$dbuser = 'service_user';
$dbpass = 's!iHa~l3YOs5cxf2';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

try {
    $pdo = new PDO(
        "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4",
        $dbuser,
        $dbpass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );
} catch (PDOException $e) {
    die('Database connection failed.');
}

/*
|--------------------------------------------------------------------------
| Helper Functions
|--------------------------------------------------------------------------
*/

function esc($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function redirect($url)
{
    header("Location: {$url}");
    exit;
}

/*
|--------------------------------------------------------------------------
| Admin Auth Helpers
|--------------------------------------------------------------------------
*/

function isAdminLoggedIn()
{
    return isset($_SESSION['admin_id']);
}

function requireAdmin()
{
    if (!isAdminLoggedIn()) {
        redirect('admin-login.php');
    }
}

function redirectIfAdminLoggedIn()
{
    if (isAdminLoggedIn()) {
        redirect('admin-dashboard.php');
    }
}

/*
|--------------------------------------------------------------------------
| Staff Auth Helpers
|--------------------------------------------------------------------------
*/

function isStaffLoggedIn()
{
    return isset($_SESSION['staff_id']);
}

function requireStaff()
{
    if (!isStaffLoggedIn()) {
        redirect('staff-login.php');
    }
}

function redirectIfStaffLoggedIn()
{
    if (isStaffLoggedIn()) {
        redirect('staff-dashboard.php');
    }
}