<?php
declare(strict_types=1);

if (!function_exists('comm_h')) {
    function comm_h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
function comm_user_id(): int {
    foreach (['user_id','ss_user_id','id','uid','staffid'] as $key) {
        if (!empty($_SESSION[$key]) && is_numeric($_SESSION[$key])) return (int)$_SESSION[$key];
    }
    return 0;
}
function comm_random_token(int $bytes = 32): string { return rtrim(strtr(base64_encode(random_bytes($bytes)), '+/', '-_'), '='); }
function comm_hash_token(string $token): string { return hash('sha256', $token); }
function comm_base_url(): string {
    $https = !empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off';
    return ($https ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? '');
}
function comm_log(PDO $pdo, int $orderId, string $channel, string $action, array $extra=[]): void {
    $stmt=$pdo->prepare("INSERT INTO communication_log(order_id,user_id,channel,action,recipient,subject,document_type,document_name,status,notes) VALUES(:order_id,:user_id,:channel,:action,:recipient,:subject,:document_type,:document_name,:status,:notes)");
    $stmt->execute([
      ':order_id'=>$orderId, ':user_id'=>comm_user_id() ?: null, ':channel'=>$channel, ':action'=>$action,
      ':recipient'=>$extra['recipient']??null, ':subject'=>$extra['subject']??null,
      ':document_type'=>$extra['document_type']??null, ':document_name'=>$extra['document_name']??null,
      ':status'=>$extra['status']??'completed', ':notes'=>$extra['notes']??null,
    ]);
}
function comm_issue_outlook_token(PDO $pdo, int $orderId): string {
    $userId=comm_user_id(); if($userId<=0) throw new RuntimeException('Your RoomZ login session is invalid.');
    $plain=strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', comm_random_token(12)), 0, 10));
    $stmt=$pdo->prepare("INSERT INTO communication_outlook_tokens(token_hash,user_id,order_id,expires_at,created_ip) VALUES(:hash,:uid,:oid,DATE_ADD(NOW(), INTERVAL 10 MINUTE),:ip)");
    $stmt->execute([':hash'=>comm_hash_token($plain),':uid'=>$userId,':oid'=>$orderId,':ip'=>$_SERVER['REMOTE_ADDR']??null]);
    return $plain;
}
function comm_booking(PDO $pdo, int $orderId): array {
    $stmt=$pdo->prepare("SELECT o.id,o.order_no,o.check_in,o.check_out,o.status,TRIM(CONCAT(COALESCE(g.firstname,''),' ',COALESCE(g.lastname,''))) guest_name,TRIM(CONCAT(COALESCE(a.firstname,''),' ',COALESCE(a.lastname,''))) agent_name FROM orders o LEFT JOIN guests g ON g.id=o.guest_id LEFT JOIN agents a ON a.id=o.agent_id WHERE o.id=:id LIMIT 1");
    $stmt->execute([':id'=>$orderId]);
    $row=$stmt->fetch(PDO::FETCH_ASSOC); if(!$row) throw new RuntimeException('Booking not found.'); return $row;
}
