<?php
/**
 * Artifact Execution & On-Site Inspection Portal
 * Location: public_html/team/artifact_executor.php
 */

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';
$user_name = trim(($_SESSION['first_name'] ?? '') . ' ' . ($_SESSION['last_name'] ?? '')) ?: 'Site Inspector';
$company_name = $_SESSION['company_name'] ?? 'Company Name';

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

if (empty($artifact_id)) {
    header("Location: dashboard.php?err=missing_artifact");
    exit;
}

// ==========================================
// 1. FETCH ARTIFACT & PROJECT DETAILS
// ==========================================
try {
    $stmt_art = $pdo->prepare("
        SELECT pa.*, p.id AS project_id, p.project_name, p.project_code, p.address, p.address AS site_address, p.status AS project_status,
               ep.id AS partner_id, ep.person_name AS partner_person_name, ep.company_name AS partner_company_name
        FROM project_artifacts pa
        JOIN projects p ON pa.project_id = p.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 not found or access denied.");
    }

    // Fetch Template & Fields
    $stmt_flds = $pdo->prepare("
        SELECT * FROM artifact_template_fields 
        WHERE template_id = ? 
        ORDER BY sort_order ASC
    ");
    $stmt_flds->execute([$artifact['template_id']]);
    $fields = $stmt_flds->fetchAll();

} catch (Exception $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}

// ==========================================
// 2. HANDLE FORM SUBMISSION (SAVE DRAFT / COMPLETE)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save_draft';

    if ($action === 'delete_file') {
        $file_id = trim($_POST['file_id'] ?? '');
        try {
            $stmt_f = $pdo->prepare("SELECT * FROM artifact_files WHERE id = ? AND project_artifact_id = ?");
            $stmt_f->execute([$file_id, $artifact_id]);
            $file_row = $stmt_f->fetch();
            if ($file_row) {
                $actual_file = __DIR__ . '/../' . ltrim($file_row['file_path'], '/');
                if (file_exists($actual_file)) {
                    @unlink($actual_file);
                }
                $stmt_del = $pdo->prepare("DELETE FROM artifact_files WHERE id = ?");
                $stmt_del->execute([$file_id]);
                $action_success = "Photo attachment removed successfully.";
            }
        } catch (Exception $e) {
            $action_error = "Error deleting file: " . $e->getMessage();
        }
    } 
    elseif ($action === 'save_draft' || $action === 'complete_artifact') {
        try {
            $pdo->beginTransaction();

            // 1. Save field responses
            foreach ($fields as $f) {
                $f_id = $f['id'];
                $f_type = $f['field_type'];
                $field_input_key = 'field_' . $f_id;

                $val_text = null;
                $val_choice = null;

                if ($f_type === 'MULTI_CHOICE') {
                    $selected_opts = $_POST[$field_input_key] ?? [];
                    if (is_array($selected_opts)) {
                        $val_choice = json_encode(array_values($selected_opts));
                    }
                } elseif ($f_type === 'SINGLE_CHOICE' || $f_type === 'CHECKBOX' || $f_type === 'DROPDOWN' || $f_type === 'TEXT' || $f_type === 'TEXTAREA') {
                    if (isset($_POST[$field_input_key])) {
                        $val_text = trim((string)$_POST[$field_input_key]);
                    }
                }

                // Optional inspector notes per question
                $notes_key = 'notes_' . $f_id;
                if (!empty($_POST[$notes_key])) {
                    $note_val = trim($_POST[$notes_key]);
                    if ($val_text !== null) {
                        $val_text .= " [Remark: " . $note_val . "]";
                    } else {
                        $val_text = "[Remark: " . $note_val . "]";
                    }
                }

                if ($val_text !== null || $val_choice !== null) {
                    $resp_id = 'resp_' . bin2hex(random_bytes(6));
                    $stmt_resp = $pdo->prepare("
                        INSERT INTO artifact_responses (id, project_artifact_id, field_id, value_text, value_choice_json)
                        VALUES (?, ?, ?, ?, ?)
                        ON DUPLICATE KEY UPDATE 
                            value_text = VALUES(value_text),
                            value_choice_json = VALUES(value_choice_json),
                            updated_at = NOW()
                    ");
                    $stmt_resp->execute([$resp_id, $artifact_id, $f_id, $val_text, $val_choice]);
                }
            }

            // 2. Handle File / Photo Uploads
            if (!empty($_FILES)) {
                $upload_base_dir = __DIR__ . '/../uploads/artifacts/';
                if (!is_dir($upload_base_dir)) {
                    @mkdir($upload_base_dir, 0777, true);
                }

                foreach ($_FILES as $input_name => $file_data) {
                    if (empty($file_data['name'])) continue;

                    // Support multiple or single files
                    $file_names = is_array($file_data['name']) ? $file_data['name'] : [$file_data['name']];
                    $file_tmps = is_array($file_data['tmp_name']) ? $file_data['tmp_name'] : [$file_data['tmp_name']];
                    $file_sizes = is_array($file_data['size']) ? $file_data['size'] : [$file_data['size']];
                    $file_types = is_array($file_data['type']) ? $file_data['type'] : [$file_data['type']];
                    $file_errors = is_array($file_data['error']) ? $file_data['error'] : [$file_data['error']];

                    for ($i = 0; $i < count($file_names); $i++) {
                        if ($file_errors[$i] !== UPLOAD_ERR_OK || empty($file_tmps[$i])) continue;

                        $orig_name = basename($file_names[$i]);
                        $ext = strtolower(pathinfo($orig_name, PATHINFO_EXTENSION));
                        $allowed = ['jpg', 'jpeg', 'png', 'webp', 'pdf'];

                        if (in_array($ext, $allowed)) {
                            $safe_name = 'qc_' . $artifact_id . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                            $target_path = $upload_base_dir . $safe_name;

                            if (move_uploaded_file($file_tmps[$i], $target_path)) {
                                $file_db_id = 'file_' . bin2hex(random_bytes(6));
                                $rel_path = 'uploads/artifacts/' . $safe_name;

                                $stmt_ins_file = $pdo->prepare("
                                    INSERT INTO artifact_files (id, project_artifact_id, file_name, file_path, file_type, file_size_bytes, uploaded_by_type, uploaded_by_name, uploaded_at)
                                    VALUES (?, ?, ?, ?, ?, ?, 'TEAM', ?, NOW())
                                ");
                                $stmt_ins_file->execute([
                                    $file_db_id,
                                    $artifact_id,
                                    $orig_name,
                                    $rel_path,
                                    $file_types[$i] ?: 'image/jpeg',
                                    (int)$file_sizes[$i],
                                    $user_name
                                ]);
                            }
                        }
                    }
                }
            }

            // 3. Update Artifact Status & Signature
            $sig_data = trim($_POST['signature_data'] ?? '');
            $signer_name = trim($_POST['completed_by_name'] ?? $user_name);

            if ($action === 'complete_artifact') {
                $stmt_upd_art = $pdo->prepare("
                    UPDATE project_artifacts 
                    SET status = 'COMPLETED',
                        completed_at = NOW(),
                        completed_by_name = ?,
                        signature_data = CASE WHEN ? != '' THEN ? ELSE signature_data END,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt_upd_art->execute([$signer_name, $sig_data, $sig_data, $artifact_id]);

                // Audit log
                try {
                    $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'ARTIFACT_COMPLETED', ?)");
                    $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Completed & signed artifact: {$artifact['title']} on project {$artifact['project_code']}"]);
                } catch (Exception $logEx) {}

                $action_success = "Inspection checklist '{$artifact['title']}' has been officially verified, signed, and finalized!";
            } else {
                $stmt_upd_art = $pdo->prepare("
                    UPDATE project_artifacts 
                    SET status = 'IN_PROGRESS',
                        signature_data = CASE WHEN ? != '' THEN ? ELSE signature_data END,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt_upd_art->execute([$sig_data, $sig_data, $artifact_id]);

                // Audit log
                try {
                    $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'ARTIFACT_SAVED_DRAFT', ?)");
                    $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Saved progress draft for artifact: {$artifact['title']}"]);
                } catch (Exception $logEx) {}

                $action_success = "Draft progress successfully saved. You can return anytime to continue.";
            }

            $pdo->commit();

            // Refresh artifact data
            $stmt_art->execute([$artifact_id, $account_id]);
            $artifact = $stmt_art->fetch();

        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $action_error = "Failed to save checklist: " . $e->getMessage();
        }
    }
}

// ==========================================
// 3. FETCH EXISTING RESPONSES & UPLOADED FILES
// ==========================================
$responses_map = [];
try {
    $stmt_r = $pdo->prepare("SELECT * FROM artifact_responses WHERE project_artifact_id = ?");
    $stmt_r->execute([$artifact_id]);
    $resp_rows = $stmt_r->fetchAll();
    foreach ($resp_rows as $r) {
        $responses_map[$r['field_id']] = $r;
    }
} catch (Exception $e) {}

$uploaded_files = [];
try {
    $stmt_fls = $pdo->prepare("SELECT * FROM artifact_files WHERE project_artifact_id = ? ORDER BY uploaded_at DESC");
    $stmt_fls->execute([$artifact_id]);
    $uploaded_files = $stmt_fls->fetchAll();
} catch (Exception $e) {}

$is_completed = ($artifact['status'] === 'COMPLETED');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QC Execution: <?php echo htmlspecialchars($artifact['title']); ?> - MiBuildqc</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; }
        .choice-btn.active-pass { background-color: #ecfdf5; border-color: #10b981; color: #047857; font-weight: 700; }
        .choice-btn.active-fail { background-color: #fff1f2; border-color: #f43f5e; color: #be123c; font-weight: 700; }
        .choice-btn.active-na { background-color: #f1f5f9; border-color: #64748b; color: #334155; font-weight: 700; }
        .choice-btn.active-custom { background-color: #eef2ff; border-color: #6366f1; color: #4338ca; font-weight: 700; }
    </style>
</head>
<body class="bg-slate-100/80 min-h-screen text-slate-800 font-sans antialiased flex flex-col">

    <!-- Top Primary Navigation Bar -->
    <header class="bg-white border-b border-slate-200 sticky top-0 z-30 shadow-xs">
        <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
            <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" title="Back to Project">
                    <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>
                </a>
                <div>
                    <span class="text-xs font-bold text-slate-400 block font-mono"><?php echo htmlspecialchars($artifact['project_code']); ?></span>
                    <h1 class="text-sm font-bold text-slate-900 truncate max-w-xs sm:max-w-md"><?php echo htmlspecialchars($artifact['title']); ?></h1>
                </div>
            </div>

            <div class="flex items-center gap-3">
                <span class="px-2.5 py-1 rounded-full text-xs font-bold border <?php 
                    echo $is_completed ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 
                         ($artifact['status'] === 'IN_PROGRESS' ? 'bg-amber-50 text-amber-700 border-amber-200' : 'bg-slate-100 text-slate-700 border-slate-200'); 
                ?>">
                    ● <?php echo htmlspecialchars($artifact['status']); ?>
                </span>

                <?php if ($is_completed): ?>
                    <a href="artifact_pdf.php?artifact_id=<?php echo urlencode($artifact['id']); ?>" target="_blank" class="px-3 py-1.5 rounded-lg bg-indigo-50 text-indigo-700 border border-indigo-200 text-xs font-bold hover:bg-indigo-100 transition-colors flex items-center gap-1">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
                        <span>PDF Report</span>
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </header>

    <!-- Main Container -->
    <main class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6 flex-1 w-full">

        <!-- Flash Messages -->
        <?php if ($action_success): ?>
            <div class="p-4 rounded-2xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-xs flex items-center justify-between shadow-xs">
                <div class="flex items-center gap-2">
                    <span class="text-base">✓</span>
                    <span><?php echo $action_success; ?></span>
                </div>
                <button onclick="this.parentElement.remove()" class="text-emerald-600 font-bold ml-4">✕</button>
            </div>
        <?php endif; ?>

        <?php if ($action_error): ?>
            <div class="p-4 rounded-2xl bg-rose-50 border border-rose-200 text-rose-800 text-xs flex items-center justify-between shadow-xs">
                <div class="flex items-center gap-2">
                    <span class="text-base">⚠️</span>
                    <span><?php echo $action_error; ?></span>
                </div>
                <button onclick="this.parentElement.remove()" class="text-rose-600 font-bold ml-4">✕</button>
            </div>
        <?php endif; ?>

        <!-- Project & Artifact Context Card -->
        <div class="bg-white rounded-2xl border border-slate-200 p-6 shadow-xs space-y-4">
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                <div>
                    <div class="flex items-center gap-2">
                        <span class="text-xs font-mono font-bold bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded-md border border-indigo-200">
                            <?php echo htmlspecialchars($artifact['project_code']); ?>
                        </span>
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-wider">
                            <?php echo str_replace('_', ' ', htmlspecialchars($artifact['type'])); ?>
                        </span>
                    </div>
                    <h2 class="text-xl font-extrabold text-slate-900 mt-1"><?php echo htmlspecialchars($artifact['project_name']); ?></h2>
                    <p class="text-xs text-slate-500 mt-0.5"><?php echo htmlspecialchars($artifact['site_address'] ?: 'On-Site Location'); ?></p>
                </div>

                <div class="p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs text-right sm:min-w-[180px]">
                    <div class="text-slate-400 text-[10px] uppercase font-bold tracking-wider">Assigned Subcontractor</div>
                    <div class="font-bold text-slate-800 mt-0.5">
                        <?php echo htmlspecialchars($artifact['partner_person_name'] ?: 'Internal MiBuildqc Team'); ?>
                    </div>
                    <?php if ($artifact['partner_company_name']): ?>
                        <div class="text-[11px] text-indigo-600 font-medium"><?php echo htmlspecialchars($artifact['partner_company_name']); ?></div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($is_completed): ?>
                <div class="p-4 bg-emerald-500/10 border border-emerald-500/30 rounded-xl flex items-center justify-between text-xs text-emerald-800">
                    <div class="flex items-center gap-2.5">
                        <div class="w-8 h-8 rounded-full bg-emerald-600 text-white flex items-center justify-center font-bold">✓</div>
                        <div>
                            <span class="font-bold block">Sign-Off Completed on <?php echo date('M j, Y a	 g:i A', strtotime($artifact['completed_at'])); ?></span>
                            <span class="text-emerald-700 text-[11px]">Inspector: <?php echo htmlspecialchars($artifact['completed_by_name']); ?></span>
                        </div>
                    </div>
                    <a href="artifact_pdf.php?artifact_id=<?php echo urlencode($artifact['id']); ?>" target="_blank" class="px-3.5 py-1.5 rounded-lg bg-emerald-600 text-white font-bold hover:bg-emerald-700 shadow-xs">
                        Download PDF Certificate
                    </a>
                </div>
            <?php endif; ?>
        </div>

        <!-- Main Execution Form -->
        <form id="executor-form" action="artifact_executor.php?artifact_id=<?php echo urlencode($artifact_id); ?>" method="POST" enctype="multipart/form-data" class="space-y-6">
            <input type="hidden" name="artifact_id" value="<?php echo htmlspecialchars($artifact_id); ?>">
            <input type="hidden" name="action" id="form-action-input" value="save_draft">
            <input type="hidden" name="signature_data" id="signature-data-input" value="">

            <!-- Questions / Criteria List -->
            <div class="space-y-4">
                <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                    <h3 class="text-sm font-bold text-slate-900 uppercase tracking-wider flex items-center gap-2">
                        <span>Inspection Questions & Field Records (<?php echo count($fields); ?>)</span>
                    </h3>
                    <span class="text-xs text-slate-500 font-medium">Fields marked with <span class="text-rose-500 font-bold">*</span> are required</span>
                </div>

                <?php if (empty($fields)): ?>
                    <div class="bg-white rounded-2xl border border-slate-200 p-8 text-center text-xs text-slate-500">
                        No fields or questions configured for this artifact template.
                    </div>
                <?php else: ?>
                    <?php foreach ($fields as $index => $f): 
                        $f_id = $f['id'];
                        $raw_type = trim((string)($f['field_type'] ?? ''));
                        $f_type = strtoupper($raw_type);
                        $label_lower = strtolower($f['field_label'] ?? '');
                        
                        // Parse options
                        $opts = [];
                        if (!empty($f['options_json'])) {
                            $opts = json_decode($f['options_json'], true) ?: [];
                        }

                        // Robust type inference for photos, choices, or signatures if type is ambiguous
                        if (empty($f_type) || $f_type === 'TEXT' || $f_type === 'PHOTO') {
                            if ($f_type === 'PHOTO' || strpos($label_lower, 'photo') !== false || strpos($label_lower, 'picture') !== false || strpos($label_lower, 'image') !== false || strpos($label_lower, 'evidence') !== false || strpos($label_lower, 'upload') !== false || strpos($label_lower, 'attachment') !== false) {
                                $f_type = 'PHOTO_UPLOAD';
                            } elseif (strpos($label_lower, 'signature') !== false || strpos($label_lower, 'sign-off') !== false) {
                                $f_type = 'SIGNATURE';
                            } elseif (!empty($opts)) {
                                $f_type = 'SINGLE_CHOICE';
                            } elseif (empty($f_type)) {
                                $f_type = 'TEXT';
                            }
                        }
                        
                        $is_photo_type = in_array($f_type, ['PHOTO_UPLOAD', 'PHOTO_EVIDENCE', 'PHOTO', 'IMAGE', 'IMAGE_UPLOAD', 'FILE', 'FILE_UPLOAD', 'DOCUMENT_UPLOAD']);

                        $current_resp = $responses_map[$f_id] ?? null;
                        $saved_text = $current_resp['value_text'] ?? '';
                        $saved_choice_arr = [];
                        if (!empty($current_resp['value_choice_json'])) {
                            $saved_choice_arr = json_decode($current_resp['value_choice_json'], true) ?: [];
                        }
                    ?>
                        <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-xs space-y-3 hover:border-slate-300 transition-colors">
                            <div class="flex items-start justify-between gap-3">
                                <div>
                                    <div class="flex items-center gap-2">
                                        <span class="w-6 h-6 rounded-full bg-slate-100 text-slate-700 flex items-center justify-center text-xs font-bold shrink-0 border border-slate-200">
                                            <?php echo ($index + 1); ?>
                                        </span>
                                        <label class="text-sm font-bold text-slate-900">
                                            <?php echo htmlspecialchars($f['field_label']); ?>
                                            <?php if ($f['is_required']): ?>
                                                <span class="text-rose-500 font-bold">*</span>
                                            <?php endif; ?>
                                        </label>
                                    </div>
                                    <?php if (!empty($f['help_text'])): ?>
                                        <p class="text-xs text-slate-500 mt-1 ml-8"><?php echo htmlspecialchars($f['help_text']); ?></p>
                                    <?php endif; ?>
                                </div>

                                <span class="text-[10px] font-bold px-2.5 py-1 rounded-md <?php echo $is_photo_type ? 'bg-indigo-50 text-indigo-700 border-indigo-200' : 'bg-slate-50 text-slate-600 border-slate-200'; ?> border shrink-0 flex items-center gap-1">
                                    <?php if ($is_photo_type): ?>
                                        <span>📷</span>
                                    <?php endif; ?>
                                    <span><?php echo str_replace('_', ' ', htmlspecialchars($f_type)); ?></span>
                                </span>
                            </div>

                            <!-- Field Specific Inputs -->
                            <div class="ml-8 pt-1">
                                <?php if ($f_type === 'SINGLE_CHOICE'): 
                                    $choice_list = !empty($opts) ? $opts : ['Pass', 'Fail', 'N/A'];
                                ?>
                                    <div class="flex flex-wrap gap-2">
                                        <?php foreach ($choice_list as $opt): 
                                            $is_selected = (trim($saved_text) === trim($opt));
                                            $opt_lower = strtolower($opt);
                                            $is_pass = strpos($opt_lower, 'pass') !== false;
                                            $is_fail = strpos($opt_lower, 'fail') !== false;
                                            $is_na = strpos($opt_lower, 'n/a') !== false || strpos($opt_lower, 'na') !== false;
                                            $btn_active_class = $is_selected ? ($is_pass ? 'active-pass' : ($is_fail ? 'active-fail' : ($is_na ? 'active-na' : 'active-custom'))) : 'bg-slate-50 border-slate-200 text-slate-700 hover:bg-slate-100';
                                        ?>
                                            <label class="choice-btn px-4 py-2 rounded-xl border text-xs cursor-pointer transition-all flex items-center gap-2 <?php echo $btn_active_class; ?>">
                                                <input type="radio" name="field_<?php echo $f_id; ?>" value="<?php echo htmlspecialchars($opt); ?>" <?php echo $is_selected ? 'checked' : ''; ?> class="hidden" onchange="handleRadioSelect(this)">
                                                <span><?php echo htmlspecialchars($opt); ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>

                                <?php elseif ($f_type === 'MULTI_CHOICE'): 
                                    $choice_list = !empty($opts) ? $opts : ['Option 1', 'Option 2', 'Option 3'];
                                ?>
                                    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2">
                                        <?php foreach ($choice_list as $opt): 
                                            $is_checked = in_array($opt, $saved_choice_arr);
                                        ?>
                                            <label class="flex items-center gap-2 p-2.5 rounded-xl border border-slate-200 hover:border-slate-300 bg-slate-50/60 cursor-pointer text-xs">
                                                <input type="checkbox" name="field_<?php echo $f_id; ?>[]" value="<?php echo htmlspecialchars($opt); ?>" <?php echo $is_checked ? 'checked' : ''; ?> class="w-4 h-4 rounded text-indigo-600">
                                                <span class="font-medium text-slate-800"><?php echo htmlspecialchars($opt); ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>

                                <?php elseif ($f_type === 'DROPDOWN'): ?>
                                    <select name="field_<?php echo $f_id; ?>" class="w-full max-w-md px-3.5 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500">
                                        <option value="">-- Select Choice --</option>
                                        <?php foreach ($opts as $opt): ?>
                                            <option value="<?php echo htmlspecialchars($opt); ?>" <?php echo ($saved_text === $opt) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($opt); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>

                                <?php elseif ($f_type === 'TEXT'): ?>
                                    <input type="text" name="field_<?php echo $f_id; ?>" value="<?php echo htmlspecialchars($saved_text); ?>" placeholder="Enter text response or metric measurement..." class="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500">

                                <?php elseif ($f_type === 'TEXTAREA'): ?>
                                    <textarea name="field_<?php echo $f_id; ?>" rows="3" placeholder="Enter detailed inspection observations, notes, or required rectifications..." class="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500"><?php echo htmlspecialchars($saved_text); ?></textarea>

                                <?php elseif ($f_type === 'CHECKBOX'): ?>
                                    <label class="flex items-center gap-2 cursor-pointer text-xs font-semibold text-slate-800">
                                        <input type="checkbox" name="field_<?php echo $f_id; ?>" value="1" <?php echo ($saved_text === '1' || $saved_text === 'Checked') ? 'checked' : ''; ?> class="w-4 h-4 rounded text-indigo-600">
                                        <span>Confirmed compliant with project quality requirements</span>
                                    </label>

                                <?php elseif ($is_photo_type): ?>
                                    <div class="space-y-3" id="photo-field-wrap-<?php echo $f_id; ?>">
                                        <!-- Photo Selector & Camera Box -->
                                        <div class="relative border-2 border-dashed border-slate-300 hover:border-indigo-500 bg-slate-50/80 hover:bg-indigo-50/20 rounded-2xl p-6 text-center transition-all cursor-pointer group">
                                            <input type="file" 
                                                   id="file-input-<?php echo $f_id; ?>" 
                                                   name="photos_field_<?php echo $f_id; ?>[]" 
                                                   multiple 
                                                   accept="image/*,application/pdf" 
                                                   capture="environment" 
                                                   onchange="handlePhotoFieldPreview(this, '<?php echo $f_id; ?>')" 
                                                   class="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10">
                                            
                                            <div class="flex flex-col items-center justify-center pointer-events-none">
                                                <div class="w-12 h-12 rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center mb-2 group-hover:scale-110 group-hover:bg-indigo-100 transition-all shadow-xs">
                                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                                                </div>
                                                <span class="text-xs font-bold text-slate-800 block">Tap to Open Camera or Choose Photo Evidence</span>
                                                <span class="text-[11px] text-slate-500 block mt-0.5">Supports Camera capture on mobile / tablet • JPG, PNG, WEBP (Max 10MB)</span>
                                                <div class="mt-2.5 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-indigo-600 text-white text-xs font-semibold shadow-xs">
                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                                                    <span>Select or Snap Photo</span>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Live Selected Photos Thumbnail Preview Strip -->
                                        <div id="preview-strip-<?php echo $f_id; ?>" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 hidden"></div>

                                        <!-- Optional Photo Caption / Inspector Remarks -->
                                        <div class="flex items-center gap-2">
                                            <input type="text" name="field_<?php echo $f_id; ?>" value="<?php echo htmlspecialchars($saved_text); ?>" placeholder="Optional photo caption or inspector observation..." class="w-full px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500">
                                        </div>
                                    </div>

                                <?php elseif ($f_type === 'SIGNATURE'): ?>
                                    <div class="p-3 bg-slate-50 rounded-xl border border-slate-200 text-xs text-slate-500 flex items-center gap-2">
                                        <svg class="w-4 h-4 text-indigo-600 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
                                        <span>Digital signature capture will be recorded in the final sign-off box below upon completion.</span>
                                    </div>
                                <?php else: ?>
                                    <div class="space-y-2">
                                        <input type="text" name="field_<?php echo $f_id; ?>" value="<?php echo htmlspecialchars($saved_text); ?>" placeholder="Enter response..." class="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500">
                                        <div class="flex items-center gap-2 text-xs text-slate-500">
                                            <span>Attach file (optional):</span>
                                            <input type="file" name="photos_field_<?php echo $f_id; ?>[]" multiple accept="image/*" class="text-xs text-slate-500">
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Uploaded Photos & Attachments Gallery -->
            <?php if (!empty($uploaded_files)): ?>
                <div class="bg-white rounded-2xl border border-slate-200 p-6 shadow-xs space-y-4">
                    <h3 class="text-sm font-bold text-slate-900 uppercase tracking-wider flex items-center gap-2">
                        <svg class="w-4 h-4 text-indigo-600" 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>Uploaded On-Site Photos (<?php echo count($uploaded_files); ?>)</span>
                    </h3>

                    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                        <?php foreach ($uploaded_files as $uf): 
                            $img_src = '../' . htmlspecialchars($uf['file_path']);
                        ?>
                            <div class="group relative rounded-xl border border-slate-200 overflow-hidden bg-slate-50 flex flex-col justify-between">
                                <a href="<?php echo $img_src; ?>" target="_blank" class="block aspect-square overflow-hidden bg-slate-900 flex items-center justify-center">
                                    <img src="<?php echo $img_src; ?>" alt="<?php echo htmlspecialchars($uf['file_name']); ?>" class="w-full h-full object-cover group-hover:scale-105 transition-transform" onerror="this.src='https://via.placeholder.com/150?text=File';">
                                </a>
                                <div class="p-2 text-[10px] space-y-0.5 bg-white border-t border-slate-100">
                                    <div class="font-bold text-slate-800 truncate"><?php echo htmlspecialchars($uf['file_name']); ?></div>
                                    <div class="text-slate-400"><?php echo date('M j, g:i A', strtotime($uf['uploaded_at'])); ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Digital Signature Sign-Off Box -->
            <div class="bg-white rounded-2xl border border-slate-200 p-6 shadow-xs space-y-4">
                <div class="flex items-center justify-between border-b border-slate-100 pb-3">
                    <div>
                        <h3 class="text-sm font-bold text-slate-900 uppercase tracking-wider flex items-center gap-2">
                            <span>✍️ Final Sign-Off & Verification</span>
                        </h3>
                        <p class="text-xs text-slate-500 mt-0.5">Sign below using your finger, stylus, or mouse to verify this QC artifact.</p>
                    </div>
                    <button type="button" onclick="clearSignaturePad()" class="text-xs font-semibold text-rose-600 hover:text-rose-800">
                        Clear Signature
                    </button>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-700 mb-1">Inspector / Verifier Full Name *</label>
                        <input type="text" name="completed_by_name" value="<?php echo htmlspecialchars($artifact['completed_by_name'] ?: $user_name); ?>" required class="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 mb-1">Inspection Timestamp</label>
                        <input type="text" readonly value="<?php echo date('Y-m-d H:i:s'); ?> (Current)" class="w-full px-3.5 py-2.5 bg-slate-100 border border-slate-200 rounded-xl text-xs text-slate-500 cursor-not-allowed">
                    </div>
                </div>

                <div>
                    <label class="block text-xs font-bold text-slate-700 mb-1">Signature Canvas (Touch / Mouse)</label>
                    <div class="border-2 border-dashed border-slate-300 rounded-2xl p-2 bg-slate-50/50">
                        <canvas id="signature-pad" width="600" height="150" class="w-full h-36 bg-white rounded-xl touch-none cursor-crosshair border border-slate-200 shadow-2xs"></canvas>
                    </div>
                </div>
            </div>

            <!-- Bottom Sticky Action Bar -->
            <div class="p-4 bg-white rounded-2xl border border-slate-200 shadow-lg flex flex-col sm:flex-row items-center justify-between gap-3 sticky bottom-4 z-20">
                <a href="project_details.php?id=<?php echo urlencode($artifact['project_id']); ?>" class="text-xs font-bold text-slate-600 hover:text-slate-900 px-4 py-2">
                    Cancel & Return
                </a>

                <div class="flex items-center gap-3 w-full sm:w-auto">
                    <button type="button" onclick="submitExecutionForm('save_draft')" class="flex-1 sm:flex-none px-5 py-2.5 rounded-xl border border-slate-300 bg-white hover:bg-slate-50 text-slate-700 text-xs font-bold transition-all shadow-2xs">
                        Save Progress Draft
                    </button>
                    <button type="button" onclick="submitExecutionForm('complete_artifact')" class="flex-1 sm:flex-none px-6 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold transition-all shadow-sm flex items-center justify-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="M5 13l4 4L19 7"></path></svg>
                        <span>Finalize & Sign Off</span>
                    </button>
                </div>
            </div>

        </form>

    </main>

    <!-- Canvas Signature & Interaction Engine -->
    <script>
        const canvas = document.getElementById('signature-pad');
        const ctx = canvas.getContext('2d');
        let isDrawing = false;
        let hasSigned = false;

        function resizeCanvas() {
            const rect = canvas.getBoundingClientRect();
            canvas.width = rect.width;
            canvas.height = rect.height;
            ctx.strokeStyle = '#1e293b';
            ctx.lineWidth = 2.5;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
        }
        window.addEventListener('resize', resizeCanvas);
        resizeCanvas();

        function getCanvasPos(e) {
            const rect = canvas.getBoundingClientRect();
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            const clientY = e.touches ? e.touches[0].clientY : e.clientY;
            return {
                x: clientX - rect.left,
                y: clientY - rect.top
            };
        }

        function startDrawing(e) {
            isDrawing = true;
            hasSigned = true;
            const pos = getCanvasPos(e);
            ctx.beginPath();
            ctx.moveTo(pos.x, pos.y);
            if (e.cancelable) e.preventDefault();
        }

        function draw(e) {
            if (!isDrawing) return;
            const pos = getCanvasPos(e);
            ctx.lineTo(pos.x, pos.y);
            ctx.stroke();
            if (e.cancelable) e.preventDefault();
        }

        function stopDrawing(e) {
            if (isDrawing) {
                ctx.closePath();
                isDrawing = false;
            }
        }

        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseleave', stopDrawing);

        canvas.addEventListener('touchstart', startDrawing, { passive: false });
        canvas.addEventListener('touchmove', draw, { passive: false });
        canvas.addEventListener('touchend', stopDrawing);

        function clearSignaturePad() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            hasSigned = false;
            document.getElementById('signature-data-input').value = '';
        }

        function handleRadioSelect(radioEl) {
            const container = radioEl.closest('.flex');
            container.querySelectorAll('.choice-btn').forEach(btn => {
                btn.className = 'choice-btn px-4 py-2 rounded-xl border text-xs cursor-pointer transition-all flex items-center gap-2 bg-slate-50 border-slate-200 text-slate-700 hover:bg-slate-100';
            });
            const parentLabel = radioEl.closest('.choice-btn');
            const val = (radioEl.value || '').toLowerCase();
            if (val.includes('pass')) {
                parentLabel.className = 'choice-btn px-4 py-2 rounded-xl border text-xs cursor-pointer transition-all flex items-center gap-2 active-pass';
            } else if (val.includes('fail')) {
                parentLabel.className = 'choice-btn px-4 py-2 rounded-xl border text-xs cursor-pointer transition-all flex items-center gap-2 active-fail';
            } else if (val.includes('na') || val.includes('n/a')) {
                parentLabel.className = 'choice-btn px-4 py-2 rounded-xl border text-xs cursor-pointer transition-all flex items-center gap-2 active-na';
            } else {
                parentLabel.className = 'choice-btn px-4 py-2 rounded-xl border text-xs cursor-pointer transition-all flex items-center gap-2 active-custom';
            }
        }

        function handlePhotoFieldPreview(input, fieldId) {
            const container = document.getElementById('preview-strip-' + fieldId);
            if (!container) return;
            container.innerHTML = '';
            
            if (input.files && input.files.length > 0) {
                container.classList.remove('hidden');
                Array.from(input.files).forEach((file) => {
                    const card = document.createElement('div');
                    card.className = 'relative rounded-xl border border-slate-200 bg-white overflow-hidden shadow-2xs p-1.5 space-y-1';
                    
                    const isImg = file.type.startsWith('image/');
                    const previewEl = document.createElement('div');
                    previewEl.className = 'aspect-square rounded-lg overflow-hidden bg-slate-100 flex items-center justify-center relative';
                    
                    if (isImg) {
                        const img = document.createElement('img');
                        img.className = 'w-full h-full object-cover';
                        img.src = URL.createObjectURL(file);
                        previewEl.appendChild(img);
                    } else {
                        previewEl.innerHTML = '<span class="text-xs font-bold text-slate-500 font-mono">📄 PDF</span>';
                    }
                    
                    const metaEl = document.createElement('div');
                    metaEl.className = 'px-1 text-[10px] truncate text-slate-700 font-bold';
                    metaEl.innerText = file.name;
                    
                    const sizeEl = document.createElement('div');
                    sizeEl.className = 'px-1 text-[9px] text-slate-400';
                    sizeEl.innerText = (file.size / 1024 / 1024).toFixed(2) + ' MB';
                    
                    card.appendChild(previewEl);
                    card.appendChild(metaEl);
                    card.appendChild(sizeEl);
                    container.appendChild(card);
                });
            } else {
                container.classList.add('hidden');
            }
        }

        function submitExecutionForm(actionType) {
            document.getElementById('form-action-input').value = actionType;
            if (hasSigned) {
                document.getElementById('signature-data-input').value = canvas.toDataURL('image/png');
            }
            document.getElementById('executor-form').submit();
        }
    </script>

</body>
</html>