<?php
// ============================================================
//  HHP  config.php — include at the top of every PHP file
// ============================================================

// ── Database ─────────────────────────────────────────────────
define('DB_HOST', 'localhost');
define('DB_NAME', 'hammerheadstaffi_db');
define('DB_USER', 'hammerheadstaffi_db');
define('DB_PASS', 'Y_472z(t9LL~@]tR');

// ── Paths ─────────────────────────────────────────────────────
define('UPLOAD_DIR', __DIR__ . '/uploads/');
define('UPLOAD_URL', '/uploads/');
define('BASE_URL',   'https://workspace.hammerheadstaffing.com');   // ← set this

// ── SMTP — replace with real credentials ─────────────────────
define('SMTP_HOST',      'smtp.zeptomail.com');
define('SMTP_PORT',      587);
define('SMTP_USER',      'no-reply@hammerheadstaffing.com');
define('SMTP_PASS',      'wSsVR612/0KiWKwvz2Cudrg5zQxcDljyQxh/iwSo7Hf1T/yUp8c8kkedVFKuGPEXFTE6RmFG9bghnUgJ1WJbjI8qyQwGWiiF9mqRe1U4J3x17qnvhDzMXm9dmxuKKY8Pzg5rm2VoF8wi+g==');
define('SMTP_FROM',      'no-reply@hammerheadstaffing.com');
define('SMTP_FROM_NAME', 'Hammerhead Protection Inc.');

// ── Session ───────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', '1');
    ini_set('session.use_strict_mode',  '1');
    ini_set('session.cookie_samesite',  'Lax');
    session_start();
}

// ── PDO singleton ─────────────────────────────────────────────
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO(
            'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4',
            DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
             PDO::ATTR_EMULATE_PREPARES   => false]
        );
    }
    return $pdo;
}

// ── Auth guards ───────────────────────────────────────────────
function requireManagerLogin(): void {
    if (empty($_SESSION['manager_id'])) {
        header('Location: /login.php'); exit;
    }
}
function requireSuperAdmin(): void {
    if (empty($_SESSION['superadmin_id'])) {
        header('Location: /admin/login.php'); exit;
    }
}

// ── CSRF ──────────────────────────────────────────────────────
function csrfToken(): string {
    if (empty($_SESSION['csrf_token']))
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    return $_SESSION['csrf_token'];
}
function verifyCsrf(string $t): bool {
    return isset($_SESSION['csrf_token']) &&
           hash_equals($_SESSION['csrf_token'], $t);
}

// ── Session event log ─────────────────────────────────────────
function logEvent(string $type, int $uid, string $uname, string $action = 'login'): void {
    try {
        db()->prepare(
            "INSERT INTO login_sessions
             (user_type,user_id,username,ip,user_agent,action)
             VALUES (?,?,?,?,?,?)"
        )->execute([
            $type, $uid, $uname,
            $_SERVER['REMOTE_ADDR']    ?? '',
            substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 299),
            $action
        ]);
    } catch (Exception $e) { /* silent */ }
}

// Create the small RBAC core on existing installations that predate roles.
function ensureRbacSchema(): void {
    $pdo = db();
    $pdo->exec("CREATE TABLE IF NOT EXISTS roles (
      id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
      code VARCHAR(50) NOT NULL UNIQUE,
      name VARCHAR(100) NOT NULL,
      level TINYINT UNSIGNED NOT NULL,
      description VARCHAR(500) DEFAULT ''
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS user_roles (
      user_type ENUM('manager','superadmin') NOT NULL,
      user_id INT NOT NULL,
      role_id SMALLINT UNSIGNED NOT NULL,
      PRIMARY KEY (user_type,user_id,role_id),
      KEY idx_user_roles_role (role_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $seed = [
      [1,'super_admin','Super Admin / CEO',1,'Full company access, settings and approvals'],
      [2,'department_head','Department Head',2,'Assigned departments, KPIs, reports and users'],
      [3,'manager','Manager',3,'Assigned projects, teams and tasks'],
      [4,'team_lead','Team Lead',4,'Assign and review work for assigned teams'],
      [5,'employee','Employee',5,'Own tasks, notes, files and forms']
    ];
    $stmt = $pdo->prepare("INSERT INTO roles (id,code,name,level,description) VALUES (?,?,?,?,?)
                           ON DUPLICATE KEY UPDATE name=VALUES(name),level=VALUES(level),description=VALUES(description)");
    foreach ($seed as $role) $stmt->execute($role);
}
