<?php
// Generated by setup_mariadb_project.sh — edit as needed.
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'app_38808');
define('DB_USER', 'app_38808');
define('DB_PASS', '6c1a4bf7-4363-46fa-8ba9-796809ca4d02');

function db() {
  static $pdo;
  if (!$pdo) {
    $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,
    ]);
    
    if (session_status() === PHP_SESSION_NONE) {
        @session_start();
    }
    if (isset($_SESSION['user_id'])) {
        $pdo->exec("SET @app_user_id = " . (int)$_SESSION['user_id']);
    }
  }
  return $pdo;
}

/**
 * Generates the next reference number for a given type (inbound/outbound/internal)
 * Format: IN-Year-Serial or OUT-Year-Serial or INT-Year-Serial
 */
function generateRefNo($type) {
    $prefix = 'IN';
    $table = 'inbound_mail';
    if ($type === 'outbound') {
        $prefix = 'OUT';
        $table = 'outbound_mail';
    } elseif ($type === 'internal') {
        $prefix = 'INT';
        $table = 'internal_mail';
    }
    
    $year = date('Y');
    $pattern = $prefix . '-' . $year . '-%';
    
    // Query the specific table for the type
    $stmt = db()->prepare("SELECT ref_no FROM $table WHERE ref_no LIKE ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$pattern]);
    $last_ref = $stmt->fetchColumn();
    
    $serial = 1;
    if ($last_ref) {
        $parts = explode('-', $last_ref);
        if (count($parts) === 3) {
            $serial = (int)$parts[2] + 1;
        }
    }
    
    return $prefix . '-' . $year . '-' . str_pad($serial, 3, '0', STR_PAD_LEFT);
}
