<?php
/**
 * Rig N Dig - Digital Vault (Certificate Management)
 * Pioneer Suite v1.0
 */
require_once __DIR__ . '/includes/header.php';

// Auto-DB Setup (Self-Healing)
Database::execute("CREATE TABLE IF NOT EXISTS certificates (
    id INT AUTO_INCREMENT PRIMARY KEY,
    invoice_id INT,
    cert_type VARCHAR(50),
    file_path VARCHAR(255),
    serial_number VARCHAR(100),
    title VARCHAR(200),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$success = $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['cert_file'])) {
    $inv_id = (int)$_POST['invoice_id'];
    $title = sanitize($_POST['title']);
    $sn = sanitize($_POST['serial_number']);
    $type = sanitize($_POST['cert_type']);
    
    if (!empty($_FILES['cert_file']['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES['cert_file']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['pdf', 'jpg', 'jpeg', 'png'])) {
            $fname = 'CERT_' . time() . '_' . rand(100,999) . '.' . $ext;
            if (move_uploaded_file($_FILES['cert_file']['tmp_name'], UPLOAD_PATH . '/' . $fname)) {
                Database::insert(
                    "INSERT INTO certificates (invoice_id, cert_type, file_path, serial_number, title) VALUES (?, ?, ?, ?, ?)",
                    [$inv_id, $type, $fname, $sn, $title]
                );
                $success = "Certificate successfully vaulted and linked to Invoice #$inv_id.";
            } else {
                $error = "File upload failed. Ensure the uploads directory is writable.";
            }
        } else {
            $error = "Only PDF and Image files are allowed in the vault.";
        }
    }
}

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    Database::execute("DELETE FROM certificates WHERE id = ?", [$id]);
    $success = "Certificate removed from vault.";
}

$certs = Database::fetchAll("
    SELECT c.*, i.invoice_number 
    FROM certificates c 
    LEFT JOIN invoices i ON c.invoice_id = i.id 
    ORDER BY c.created_at DESC
");
$invoices = Database::fetchAll("SELECT id, invoice_number FROM invoices ORDER BY id DESC LIMIT 50");
?>

<div class="p-6 max-w-7xl mx-auto">
    <div class="flex items-center justify-between mb-8">
        <div>
            <h1 class="text-3xl font-black font-display text-white italic tracking-tighter">DIGITAL <span class="text-orange-500">VAULT</span></h1>
            <p class="text-gray-500 text-xs font-bold uppercase tracking-widest mt-1">Industrial Certificate & Technical Data Management</p>
        </div>
        <div class="bg-navy-800 border border-orange-600/30 px-4 py-2 rounded-xl flex items-center gap-3">
            <span class="text-orange-500 text-xl">🛡️</span>
            <div>
                <div class="text-[10px] font-black text-white uppercase tracking-widest">Vault Security</div>
                <div class="text-[9px] text-gray-500 font-bold uppercase">Encrypted Asset Repository</div>
            </div>
        </div>
    </div>

    <?php if ($success): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 p-4 rounded-xl mb-6 text-sm"><?= $success ?></div><?php endif; ?>
    <?php if ($error): ?><div class="bg-red-600/10 border border-red-600/30 text-red-400 p-4 rounded-xl mb-6 text-sm"><?= $error ?></div><?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Upload Form -->
        <div class="lg:col-span-1">
            <div class="card-dark p-6 border-orange-600/20">
                <h3 class="font-bold text-white mb-6 uppercase tracking-widest text-sm flex items-center gap-2">
                    <span class="w-2 h-2 rounded-full bg-orange-500 animate-pulse"></span>
                    Vault New Asset
                </h3>
                <form method="POST" enctype="multipart/form-data" class="space-y-5">
                    <div>
                        <label class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 block">Link to Invoice</label>
                        <select name="invoice_id" class="input-field w-full" required>
                            <option value="">Select Invoice...</option>
                            <?php foreach ($invoices as $i): ?>
                                <option value="<?= $i['id'] ?>"><?= e($i['invoice_number']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 block">Document Title</label>
                        <input type="text" name="title" class="input-field w-full" placeholder="e.g. API 6A Gate Valve MTR" required>
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 block">Serial / Heat Number</label>
                        <input type="text" name="serial_number" class="input-field w-full" placeholder="e.g. SN-88291-Q">
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 block">Certificate Type</label>
                        <select name="cert_type" class="input-field w-full">
                            <option value="MTR">Material Test Report (MTR)</option>
                            <option value="COC">Certificate of Conformance</option>
                            <option value="API">API Certification</option>
                            <option value="ISO">ISO Standard Cert</option>
                            <option value="OTHER">Other Tech Data</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 block">Upload File (PDF/IMG)</label>
                        <input type="file" name="cert_file" class="text-xs text-gray-500 file:bg-navy-700 file:border-none file:text-white file:px-4 file:py-2 file:rounded-lg file:mr-4" required>
                    </div>
                    <button type="submit" class="btn-primary w-full py-3 font-black uppercase text-xs tracking-widest">Secure in Vault</button>
                </form>
            </div>
        </div>

        <!-- Certificate List -->
        <div class="lg:col-span-2">
            <div class="card-dark overflow-hidden border-navy-700">
                <table class="w-full text-left">
                    <thead class="bg-navy-800 border-b border-navy-700">
                        <tr>
                            <th class="px-6 py-4 text-[10px] font-black text-gray-400 uppercase tracking-widest">Document</th>
                            <th class="px-6 py-4 text-[10px] font-black text-gray-400 uppercase tracking-widest">Linked Invoice</th>
                            <th class="px-6 py-4 text-[10px] font-black text-gray-400 uppercase tracking-widest">Serial #</th>
                            <th class="px-6 py-4 text-[10px] font-black text-gray-400 uppercase tracking-widest">Date Vaulted</th>
                            <th class="px-6 py-4"></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-navy-700">
                        <?php if (empty($certs)): ?>
                        <tr><td colspan="5" class="px-6 py-12 text-center text-gray-500 text-sm">Vault is empty. Start securing technical assets.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($certs as $c): ?>
                        <tr class="hover:bg-navy-800/50 transition-colors">
                            <td class="px-6 py-4">
                                <div class="text-sm font-bold text-white"><?= e($c['title']) ?></div>
                                <div class="text-[10px] text-orange-500 font-bold uppercase tracking-widest mt-1"><?= e($c['cert_type']) ?></div>
                            </td>
                            <td class="px-6 py-4 text-xs font-mono text-gray-400"><?= e($c['invoice_number'] ?: 'N/A') ?></td>
                            <td class="px-6 py-4 text-xs font-bold text-gray-300"><?= e($c['serial_number'] ?: '—') ?></td>
                            <td class="px-6 py-4 text-[10px] font-bold text-gray-500 uppercase"><?= date('M d, Y', strtotime($c['created_at'])) ?></td>
                            <td class="px-6 py-4 text-right flex gap-3 justify-end items-center">
                                <a href="/uploads/<?= e($c['file_path']) ?>" target="_blank" class="text-orange-500 hover:text-orange-400 text-xs font-black uppercase tracking-widest">View</a>
                                <a href="?delete=<?= $c['id'] ?>" onclick="return confirm('Remove document from secure vault?')" class="text-red-600 hover:text-red-500 text-xs">✕</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
