<?php
/**
 * Quality Control Inspection PDF Report Generator & Print Certificate
 * Location: public_html/team/artifact_pdf.php
 * Handles PDF rendering, browser printing, and archival downloads
 */

require_once __DIR__ . '/../connections/connect.php';
require_once __DIR__ . '/../includes/functions.php';

require_login();

$user_id = $_SESSION['user_id'];
$account_id = $_SESSION['account_id'];
$user_role = $_SESSION['role'] ?? 'TEAM_MEMBER';
$company_name = $_SESSION['company_name'] ?? 'Company Name';

$artifact_id = trim($_GET['artifact_id'] ?? '');

if (empty($artifact_id)) {
    die("Error: Missing artifact ID. <a href='dashboard.php'>Return to Dashboard</a>");
}

try {
    // 1. Fetch Company & Primary Admin Info
    $stmt_acc = $pdo->prepare("
        SELECT a.company_name, a.created_at AS account_created, u.first_name, u.last_name, u.email AS admin_email
        FROM accounts a
        LEFT JOIN users u ON a.id = u.account_id AND u.role = 'PRIMARY_ADMIN'
        WHERE a.id = ?
        LIMIT 1
    ");
    $stmt_acc->execute([$account_id]);
    $acc_info = $stmt_acc->fetch();
    if ($acc_info && !empty($acc_info['company_name'])) {
        $company_name = $acc_info['company_name'];
    }
    $primary_owner = trim(($acc_info['first_name'] ?? '') . ' ' . ($acc_info['last_name'] ?? '')) ?: 'Primary Administrator';

    // 2. Fetch Artifact, Project, and Partner Details
    $stmt_art = $pdo->prepare("
        SELECT pa.*, p.id AS project_id, p.project_name, p.project_code, p.address AS site_address, 
               p.client_name, p.client_email, p.client_mobile, p.status AS project_status,
               ep.id AS partner_id, ep.person_name AS partner_person_name, ep.company_name AS partner_company_name, ep.email AS partner_email, ep.mobile_number AS partner_mobile,
               at.title AS template_title, at.category AS template_category, at.description AS template_desc
        FROM project_artifacts pa
        JOIN projects p ON pa.project_id = p.id
        LEFT JOIN artifact_templates at ON pa.template_id = at.id
        LEFT JOIN external_partners ep ON pa.assigned_partner_id = ep.id
        WHERE pa.id = ? AND p.account_id = ?
    ");
    $stmt_art->execute([$artifact_id, $account_id]);
    $artifact = $stmt_art->fetch();

    if (!$artifact) {
        die("Error: Artifact record not found or access denied. <a href='dashboard.php'>Return to Dashboard</a>");
    }

    // 3. Fetch Configured Checklist Fields
    $stmt_fields = $pdo->prepare("
        SELECT * FROM artifact_template_fields 
        WHERE template_id = ? 
        ORDER BY sort_order ASC
    ");
    $stmt_fields->execute([$artifact['template_id']]);
    $fields = $stmt_fields->fetchAll();

    // 4. Fetch Stored Answers & Responses
    $stmt_resp = $pdo->prepare("
        SELECT * FROM artifact_responses 
        WHERE project_artifact_id = ?
    ");
    $stmt_resp->execute([$artifact_id]);
    $raw_responses = $stmt_resp->fetchAll();
    $responses_by_field = [];
    foreach ($raw_responses as $r) {
        $responses_by_field[$r['field_id']] = $r;
    }

    // 5. Fetch Uploaded Photo Evidence & Attachments
    $stmt_files = $pdo->prepare("
        SELECT * FROM artifact_files 
        WHERE project_artifact_id = ? 
        ORDER BY uploaded_at ASC
    ");
    $stmt_files->execute([$artifact_id]);
    $files = $stmt_files->fetchAll();

    // 6. Calculate Summary Metrics
    $total_questions = count($fields);
    $pass_count = 0;
    $fail_count = 0;
    $na_count = 0;
    $answered_count = 0;

    foreach ($fields as $f) {
        $f_id = $f['id'];
        $resp = $responses_by_field[$f_id] ?? null;
        if ($resp && !empty($resp['value_text'])) {
            $answered_count++;
            $val_lower = strtolower($resp['value_text']);
            if (strpos($val_lower, 'pass') !== false) {
                $pass_count++;
            } elseif (strpos($val_lower, 'fail') !== false) {
                $fail_count++;
            } elseif (strpos($val_lower, 'n/a') !== false || strpos($val_lower, 'na') !== false) {
                $na_count++;
            }
        }
    }

    $is_completed = ($artifact['status'] === 'COMPLETED');
    $report_ref_no = 'QC-REP-' . strtoupper(substr(md5($artifact['id']), 0, 8));
    $generated_date = date('F j, Y g:i A');

} catch (Exception $e) {
    die("Database error loading report: " . htmlspecialchars($e->getMessage()));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QC Report - <?php echo htmlspecialchars($artifact['project_code']); ?> - <?php echo htmlspecialchars($artifact['title']); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background-color: #f8fafc;
            color: #1e293b;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            body {
                background-color: #ffffff !important;
                padding: 0 !important;
            }
            .print-page {
                box-shadow: none !important;
                border: none !important;
                max-width: 100% !important;
                width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            .page-break {
                page-break-after: always;
            }
            tr {
                page-break-inside: avoid;
            }
        }
    </style>
</head>
<body class="p-4 sm:p-8 antialiased">

    <!-- Top Non-Printable Action Bar -->
    <div class="no-print max-w-4xl mx-auto mb-6 bg-white p-4 rounded-2xl border border-slate-200 shadow-sm flex flex-col sm:flex-row items-center justify-between gap-4">
        <div class="flex items-center gap-3">
            <a href="project_details.php?id=<?php echo urlencode($artifact['project_id']); ?>" class="p-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 transition-colors inline-flex items-center gap-1.5 text-xs font-semibold">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                <span>Project Details</span>
            </a>
            <div>
                <h1 class="text-sm font-bold text-slate-900">Official Quality Control Document</h1>
                <p class="text-[11px] text-slate-500">Certificate Reference: <span class="font-mono font-bold text-slate-700"><?php echo $report_ref_no; ?></span></p>
            </div>
        </div>

        <div class="flex items-center gap-2">
            <a href="artifact_executor.php?artifact_id=<?php echo urlencode($artifact['id']); ?>" class="px-4 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 text-xs font-bold transition-all shadow-xs">
                Edit Checklist
            </a>
            <button onclick="window.print()" class="px-5 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold transition-all shadow-sm flex items-center gap-2">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
                <span>Print / Save as PDF</span>
            </button>
        </div>
    </div>

    <!-- Official Printable Report Sheet -->
    <div class="print-page max-w-4xl mx-auto bg-white p-8 sm:p-12 rounded-2xl border border-slate-200 shadow-md space-y-8">

        <!-- Header Section -->
        <div class="border-b-2 border-slate-900 pb-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div class="space-y-1">
                <div class="flex items-center gap-2">
                    <span class="text-2xl font-extrabold tracking-tight text-slate-900">MiBuild<span class="text-indigo-600">qc</span></span>
                    <span class="text-[11px] font-bold uppercase tracking-wider px-2 py-0.5 rounded bg-indigo-50 text-indigo-700 border border-indigo-200">
                        Official QC Inspection Record
                    </span>
                </div>
                <div class="text-base font-bold text-slate-800"><?php echo htmlspecialchars($company_name); ?></div>
                <div class="text-xs text-slate-500">Quality Assurance & Compliance System</div>
            </div>

            <div class="text-left sm:text-right space-y-1">
                <div class="inline-block px-3 py-1 bg-slate-100 border border-slate-200 rounded-lg text-xs font-mono font-bold text-slate-800">
                    <?php echo $report_ref_no; ?>
                </div>
                <div class="text-[11px] text-slate-500 font-mono">Date: <?php echo $generated_date; ?></div>
                <div class="text-[11px] text-slate-500">Account Owner: <?php echo htmlspecialchars($primary_owner); ?></div>
            </div>
        </div>

        <!-- Artifact Title & Status Ribbon -->
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-5 rounded-2xl bg-slate-50 border border-slate-200">
            <div>
                <div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider"><?php echo htmlspecialchars($artifact['template_category'] ?: 'Quality Control'); ?> • <?php echo str_replace('_', ' ', htmlspecialchars($artifact['type'])); ?></div>
                <h2 class="text-xl font-bold text-slate-900 mt-0.5"><?php echo htmlspecialchars($artifact['title']); ?></h2>
                <?php if (!empty($artifact['template_desc'])): ?>
                    <p class="text-xs text-slate-500 mt-1"><?php echo htmlspecialchars($artifact['template_desc']); ?></p>
                <?php endif; ?>
            </div>

            <div class="text-left sm:text-right shrink-0">
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold border <?php echo $is_completed ? 'bg-emerald-100 text-emerald-800 border-emerald-300' : 'bg-amber-100 text-amber-800 border-amber-300'; ?>">
                    <span><?php echo $is_completed ? '✓ SIGNED & COMPLETED' : '● DRAFT / IN PROGRESS'; ?></span>
                </span>
                <?php if ($is_completed && !empty($artifact['completed_at'])): ?>
                    <div class="text-[11px] text-slate-500 font-mono mt-1">
                        Completed: <?php echo date('M j, Y g:i A', strtotime($artifact['completed_at'])); ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Metadata Two-Column Grid: Project & Contractor -->
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
            <!-- Left: Project Context -->
            <div class="p-4 rounded-xl border border-slate-200 bg-white space-y-2.5">
                <div class="text-[11px] font-bold text-slate-400 uppercase tracking-wider border-b border-slate-100 pb-1.5">
                    Project & Site Location
                </div>
                <div>
                    <span class="text-xs text-slate-400 block">Project Code & Name</span>
                    <div class="text-sm font-bold text-slate-900">
                        <span class="font-mono text-indigo-600 bg-indigo-50 px-1.5 py-0.5 rounded mr-1"><?php echo htmlspecialchars($artifact['project_code']); ?></span>
                        <?php echo htmlspecialchars($artifact['project_name']); ?>
                    </div>
                </div>
                <div>
                    <span class="text-xs text-slate-400 block">Site Physical Address</span>
                    <div class="text-xs font-semibold text-slate-800"><?php echo htmlspecialchars($artifact['site_address'] ?: 'Not Specified'); ?></div>
                </div>
                <div>
                    <span class="text-xs text-slate-400 block">Client Contact</span>
                    <div class="text-xs text-slate-700 font-medium">
                        <?php echo htmlspecialchars($artifact['client_name'] ?: 'N/A'); ?>
                        <?php if (!empty($artifact['client_email'])): ?> • <?php echo htmlspecialchars($artifact['client_email']); ?><?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Right: Subcontractor / Inspector Context -->
            <div class="p-4 rounded-xl border border-slate-200 bg-white space-y-2.5">
                <div class="text-[11px] font-bold text-slate-400 uppercase tracking-wider border-b border-slate-100 pb-1.5">
                    Assigned Inspector & Contractor
                </div>
                <div>
                    <span class="text-xs text-slate-400 block">Inspector / Contractor Name</span>
                    <div class="text-sm font-bold text-slate-900">
                        <?php echo htmlspecialchars($artifact['partner_person_name'] ?: ($artifact['completed_by_name'] ?: 'Internal Site Team')); ?>
                    </div>
                </div>
                <div>
                    <span class="text-xs text-slate-400 block">Organization / Subcontractor</span>
                    <div class="text-xs font-semibold text-indigo-700"><?php echo htmlspecialchars($artifact['partner_company_name'] ?: $company_name); ?></div>
                </div>
                <div>
                    <span class="text-xs text-slate-400 block">Verification Authority</span>
                    <div class="text-xs text-slate-700 font-medium">
                        Signed Off By: <span class="font-semibold text-slate-900"><?php echo htmlspecialchars($artifact['completed_by_name'] ?: 'Pending Verification'); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Compliance & Metric Badges -->
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div class="p-3.5 rounded-xl bg-slate-50 border border-slate-200 text-center">
                <span class="text-[10px] uppercase font-bold text-slate-400 block">Total Items</span>
                <span class="text-xl font-bold text-slate-900"><?php echo $total_questions; ?></span>
            </div>
            <div class="p-3.5 rounded-xl bg-emerald-50 border border-emerald-200 text-center">
                <span class="text-[10px] uppercase font-bold text-emerald-700 block">Passed</span>
                <span class="text-xl font-bold text-emerald-800"><?php echo $pass_count; ?></span>
            </div>
            <div class="p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-center">
                <span class="text-[10px] uppercase font-bold text-rose-700 block">Failed / Defect</span>
                <span class="text-xl font-bold text-rose-800"><?php echo $fail_count; ?></span>
            </div>
            <div class="p-3.5 rounded-xl bg-indigo-50 border border-indigo-200 text-center">
                <span class="text-[10px] uppercase font-bold text-indigo-700 block">Evidence Photos</span>
                <span class="text-xl font-bold text-indigo-800"><?php echo count($files); ?></span>
            </div>
        </div>

        <!-- Detailed Findings & Checklist Table -->
        <div class="space-y-3">
            <h3 class="text-sm font-bold text-slate-900 uppercase tracking-wider border-b border-slate-200 pb-2">
                Itemized Quality Inspection Findings
            </h3>

            <?php if (empty($fields)): ?>
                <div class="p-6 text-center text-xs text-slate-500 bg-slate-50 rounded-xl border border-slate-200">
                    No individual checklist questions defined for this artifact.
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-xs border-collapse">
                        <thead>
                            <tr class="bg-slate-100 text-slate-700 border-b border-slate-300">
                                <th class="py-2.5 px-3 font-bold w-10 text-center">#</th>
                                <th class="py-2.5 px-3 font-bold">Inspection Criterion / Question</th>
                                <th class="py-2.5 px-3 font-bold w-28 text-center">Type</th>
                                <th class="py-2.5 px-3 font-bold w-44 text-right">Recorded Value / Status</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200">
                            <?php foreach ($fields as $idx => $f): 
                                $f_id = $f['id'];
                                $resp = $responses_by_field[$f_id] ?? null;
                                $resp_val = $resp['value_text'] ?? '—';
                                $val_lower = strtolower($resp_val);
                                $is_pass = strpos($val_lower, 'pass') !== false;
                                $is_fail = strpos($val_lower, 'fail') !== false;
                                $is_na = strpos($val_lower, 'n/a') !== false || strpos($val_lower, 'na') !== false;
                            ?>
                                <tr class="hover:bg-slate-50/80 transition-colors">
                                    <td class="py-3 px-3 text-slate-400 font-mono text-center font-bold"><?php echo ($idx + 1); ?></td>
                                    <td class="py-3 px-3 space-y-1">
                                        <div class="font-bold text-slate-900"><?php echo htmlspecialchars($f['field_label']); ?></div>
                                        <?php if (!empty($f['help_text'])): ?>
                                            <div class="text-[11px] text-slate-500 italic"><?php echo htmlspecialchars($f['help_text']); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="py-3 px-3 text-center">
                                        <span class="text-[10px] font-semibold px-2 py-0.5 rounded bg-slate-100 text-slate-600 border border-slate-200">
                                            <?php echo str_replace('_', ' ', htmlspecialchars($f['field_type'])); ?>
                                        </span>
                                    </td>
                                    <td class="py-3 px-3 text-right font-medium">
                                        <?php if ($is_pass): ?>
                                            <span class="inline-block px-2.5 py-1 rounded bg-emerald-100 text-emerald-800 font-bold text-xs border border-emerald-200">
                                                ✓ <?php echo htmlspecialchars($resp_val); ?>
                                            </span>
                                        <?php elseif ($is_fail): ?>
                                            <span class="inline-block px-2.5 py-1 rounded bg-rose-100 text-rose-800 font-bold text-xs border border-rose-200">
                                                ✕ <?php echo htmlspecialchars($resp_val); ?>
                                            </span>
                                        <?php elseif ($is_na): ?>
                                            <span class="inline-block px-2.5 py-1 rounded bg-slate-100 text-slate-700 font-semibold text-xs border border-slate-200">
                                                — <?php echo htmlspecialchars($resp_val); ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-slate-900 font-semibold"><?php echo htmlspecialchars($resp_val); ?></span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Attached Photo Evidence Gallery -->
        <?php if (!empty($files)): ?>
            <div class="space-y-3 pt-4">
                <h3 class="text-sm font-bold text-slate-900 uppercase tracking-wider border-b border-slate-200 pb-2 flex items-center justify-between">
                    <span>Photographic Evidence & Site Attachments</span>
                    <span class="text-xs font-normal text-slate-500"><?php echo count($files); ?> Attached Files</span>
                </h3>

                <div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
                    <?php foreach ($files as $file): 
                        $rel_path = '../' . ltrim($file['file_path'], '/');
                        $is_img = strpos($file['file_type'] ?? '', 'image') !== false || in_array(strtolower(pathinfo($file['file_name'], PATHINFO_EXTENSION)), ['jpg','jpeg','png','webp']);
                    ?>
                        <div class="p-3 bg-slate-50 border border-slate-200 rounded-xl space-y-2">
                            <?php if ($is_img && file_exists(__DIR__ . '/' . $rel_path)): ?>
                                <img src="<?php echo htmlspecialchars($rel_path); ?>" alt="<?php echo htmlspecialchars($file['file_name']); ?>" class="w-full h-36 object-cover rounded-lg border border-slate-200">
                            <?php else: ?>
                                <div class="w-full h-36 bg-slate-200 rounded-lg flex flex-col items-center justify-center text-slate-500 gap-1 p-2 text-center">
                                    <svg class="w-8 h-8 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                                    <span class="text-[11px] font-mono font-bold truncate max-w-full"><?php echo htmlspecialchars($file['file_name']); ?></span>
                                </div>
                            <?php endif; ?>
                            <div class="text-[11px] text-slate-600 truncate font-medium"><?php echo htmlspecialchars($file['file_name']); ?></div>
                            <div class="text-[10px] text-slate-400 font-mono">Uploaded: <?php echo date('M j, Y H:i', strtotime($file['uploaded_at'])); ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Digital Sign-Off & Verification Footer -->
        <div class="pt-6 border-t-2 border-slate-900 space-y-4">
            <div class="text-xs text-slate-500 uppercase font-bold tracking-wider">
                Verification & Certification Sign-Off
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-6 p-5 bg-slate-50 rounded-2xl border border-slate-200">
                <div class="space-y-2">
                    <span class="text-[11px] text-slate-500 font-bold uppercase block">Inspector Attestation</span>
                    <p class="text-xs text-slate-600 leading-relaxed">
                        I hereby verify that the work, structural components, and installations specified in this artifact have been inspected and evaluated in accordance with project engineering specifications, building standards, and quality controls.
                    </p>
                    <div class="pt-2 text-xs">
                        <span class="text-slate-400">Sign-Off Name:</span>
                        <strong class="text-slate-900 ml-1"><?php echo htmlspecialchars($artifact['completed_by_name'] ?: 'Pending Sign-Off'); ?></strong>
                    </div>
                </div>

                <div class="flex flex-col items-center justify-center p-3 bg-white border border-slate-300 rounded-xl space-y-2">
                    <span class="text-[10px] font-bold uppercase text-slate-400">Captured Signature / Verification Token</span>
                    <?php if (!empty($artifact['signature_data']) && strpos($artifact['signature_data'], 'data:image') === 0): ?>
                        <img src="<?php echo htmlspecialchars($artifact['signature_data']); ?>" alt="Sign-Off Signature" class="max-h-20 object-contain">
                    <?php else: ?>
                        <div class="py-4 text-xs font-mono font-bold text-slate-600 text-center">
                            <?php echo htmlspecialchars($artifact['signature_data'] ?: 'Digital Token Signature Stamped'); ?>
                        </div>
                    <?php endif; ?>
                    <span class="text-[10px] text-slate-400 font-mono">Timestamp: <?php echo !empty($artifact['completed_at']) ? date('Y-m-d H:i:s T', strtotime($artifact['completed_at'])) : date('Y-m-d H:i:s T'); ?></span>
                </div>
            </div>

            <div class="text-center text-[10px] text-slate-400 pt-4 border-t border-slate-200">
                MiBuildqc Quality Control System • Generated for <?php echo htmlspecialchars($company_name); ?> • Report Ref: <?php echo $report_ref_no; ?>
            </div>
        </div>

    </div>

    <!-- Auto Print Script if print query flag present -->
    <?php if (isset($_GET['print']) && $_GET['print'] === '1'): ?>
        <script>
            window.addEventListener('load', () => {
                window.print();
            });
        </script>
    <?php endif; ?>

</body>
</html>