<?php
/**
 * سير عمل الطباعة الاحترافي
 * - approved_at, approved_by في lab_orders
 * - report_id فريد لكل تقرير
 * - print_log لتسجيل كل طباعة
 */
$config = require __DIR__ . '/../config/config.php';
$pdo = new PDO(
    'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] . ';charset=utf8mb4',
    $config['db']['user'],
    $config['db']['pass'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$changes = [];

try {
    $pdo->exec("ALTER TABLE lab_orders ADD COLUMN approved_at DATETIME NULL");
    $changes[] = "lab_orders.approved_at";
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Duplicate column') === false) $changes[] = "Error approved_at: " . $e->getMessage();
}
try {
    $pdo->exec("ALTER TABLE lab_orders ADD COLUMN approved_by INT NULL");
    $changes[] = "lab_orders.approved_by";
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Duplicate column') === false) $changes[] = "Error approved_by: " . $e->getMessage();
}
try {
    $pdo->exec("ALTER TABLE lab_orders ADD COLUMN report_id VARCHAR(32) NULL UNIQUE");
    $changes[] = "lab_orders.report_id";
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Duplicate column') === false) $changes[] = "Error report_id: " . $e->getMessage();
}

$pdo->exec("CREATE TABLE IF NOT EXISTS print_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_id INT NOT NULL,
    user_id INT NULL,
    printed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    print_type ENUM('official','normal') NOT NULL DEFAULT 'normal',
    copies INT NOT NULL DEFAULT 1,
    ip_address VARCHAR(45) NULL,
    user_agent VARCHAR(255) NULL,
    tenant_id INT NULL,
    FOREIGN KEY (order_id) REFERENCES lab_orders(id),
    INDEX idx_order (order_id),
    INDEX idx_printed_at (printed_at)
)");
$changes[] = "print_log table";

foreach ($changes as $c) echo $c . "\n";
echo "Done.\n";
