<?php
/**
 * Partner On-Site Execution Portal (Public via Token)
 * Location: public_html/partner_access.php
 */

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

$token = trim($_GET['token'] ?? '');
$error_message = '';
$artifact = null;
$partner = null;
$project = null;
$fields = [];
$responses = [];
$success_submitted = false;

if (empty($token)) {
    $error_message = "Invalid access link. Please provide a valid site security token.";
} else {
    try {
        // Query link token
        $stmt_tok = $pdo->prepare("
            SELECT pal.*, pa.id AS artifact_id, pa.title AS artifact_title, pa.type AS artifact_type, pa.status AS artifact_status,
                   pa.template_id, p.id AS project_id, p.project_name, p.project_code, p.address, p.address AS site_address,
                   ep.id AS partner_id, ep.person_name, ep.company_name, ep.email, ep.mobile_number
            FROM partner_access_links pal
            JOIN project_artifacts pa ON pal.project_artifact_id = pa.id
            JOIN projects p ON pa.project_id = p.id
            JOIN external_partners ep ON pal.partner_id = ep.id
            WHERE pal.token = ? AND pal.is_active = 1
        ");
        $stmt_tok->execute([$token]);
        $data = $stmt_tok->fetch();

        if (!$data) {
            $error_message = "This site access link is either invalid, expired, or has been revoked.";
        } elseif (strtotime($data['expires_at']) < time()) {
            $error_message = "This site access link expired on " . date('M j, Y g:i A', strtotime($data['expires_at'])) . ". Please request a refreshed link from the site project manager.";
        } else {
            $artifact = [
                'id' => $data['artifact_id'],
                'title' => $data['artifact_title'],
                'type' => $data['artifact_type'],
                'status' => $data['artifact_status'],
                'template_id' => $data['template_id']
            ];
            $partner = [
                'id' => $data['partner_id'],
                'person_name' => $data['person_name'],
                'company_name' => $data['company_name'],
                'email' => $data['email'],
                'mobile_number' => $data['mobile_number']
            ];
            $project = [
                'id' => $data['project_id'],
                'project_name' => $data['project_name'],
                'project_code' => $data['project_code'],
                'site_address' => $data['site_address']
            ];

            // Update link access count
            $stmt_upd_cnt = $pdo->prepare("UPDATE partner_access_links SET access_count = access_count + 1, last_accessed_at = NOW() WHERE id = ?");
            $stmt_upd_cnt->execute([$data['id']]);

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

            // Handle submission
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_artifact') {
                $completed_by = sanitize_input($_POST['completed_by_name'] ?? $partner['person_name']);
                $signature = $_POST['signature_data'] ?? 'Verified via Secure On-Site Link';

                // Save answers
                foreach ($fields as $f) {
                    $f_id = $f['id'];
                    $f_type = $f['field_type'];
                    $field_val = $_POST['field_' . $f_id] ?? '';
                    $val_text = null;
                    $val_choice = null;

                    if ($f_type === 'MULTI_CHOICE') {
                        if (is_array($field_val)) {
                            $val_choice = json_encode(array_values($field_val));
                            $val_text = implode(', ', $field_val);
                        }
                    } else {
                        $val_text = is_array($field_val) ? implode(', ', $field_val) : (string)$field_val;
                    }

                    $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_' . bin2hex(random_bytes(6)), $artifact['id'], $f_id, $val_text, $val_choice]);
                }

                // Handle Photo Evidence 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;

                        $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 = 'partner_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 (?, ?, ?, ?, ?, ?, 'PARTNER', ?, NOW())
                                    ");
                                    $stmt_ins_file->execute([
                                        $file_db_id,
                                        $artifact['id'],
                                        $orig_name,
                                        $rel_path,
                                        $file_types[$i] ?: 'image/jpeg',
                                        (int)$file_sizes[$i],
                                        $partner['person_name']
                                    ]);
                                }
                            }
                        }
                    }
                }

                // Update artifact status to COMPLETED
                $stmt_fin = $pdo->prepare("
                    UPDATE project_artifacts 
                    SET status = 'COMPLETED', completed_at = NOW(), completed_by_name = ?, signature_data = ?
                    WHERE id = ?
                ");
                $stmt_fin->execute([$completed_by, $signature, $artifact['id']]);

                $success_submitted = true;
                $artifact['status'] = 'COMPLETED';
            }
        }
    } catch (Exception $e) {
        $error_message = "Error loading site artifact: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>On-Site QC Execution Portal - 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; }
    </style>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen font-sans antialiased flex flex-col items-center justify-start p-4 sm:p-6">

    <div class="max-w-xl w-full mx-auto space-y-6">

        <!-- Top Header -->
        <div class="flex items-center justify-between border-b border-slate-800 pb-4">
            <div>
                <span class="text-xl font-extrabold tracking-tight text-white">MiBuild<span class="text-indigo-400">qc</span></span>
                <span class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Mobile Field Inspector</span>
            </div>
            <div class="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-[10px] font-bold">
                <span>● Secure Token Verified</span>
            </div>
        </div>

        <?php if ($error_message): ?>
            <div class="bg-rose-950/80 border border-rose-800 text-rose-200 p-6 rounded-2xl space-y-3 text-center shadow-xl">
                <div class="w-12 h-12 rounded-full bg-rose-900/50 flex items-center justify-center mx-auto text-rose-400 text-xl font-bold">⚠️</div>
                <h2 class="text-base font-bold text-rose-100">Access Restricted</h2>
                <p class="text-xs text-rose-300 leading-relaxed"><?php echo htmlspecialchars($error_message); ?></p>
            </div>
        <?php elseif ($success_submitted || $artifact['status'] === 'COMPLETED'): ?>
            <div class="bg-slate-800/90 border border-emerald-500/40 p-8 rounded-2xl space-y-4 text-center shadow-xl">
                <div class="w-16 h-16 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center mx-auto text-2xl font-bold">✓</div>
                <h2 class="text-xl font-bold text-white">QC Checklist Completed!</h2>
                <p class="text-xs text-slate-300 max-w-md mx-auto">
                    Thank you <strong><?php echo htmlspecialchars($partner['person_name']); ?></strong>. Your completed inspection sign-off for <strong><?php echo htmlspecialchars($artifact['title']); ?></strong> has been timestamped and synchronized with the project record.
                </p>
                <div class="p-3 bg-slate-900 rounded-xl text-[11px] font-mono text-slate-400 border border-slate-700">
                    Project: <?php echo htmlspecialchars($project['project_code']); ?> • <?php echo htmlspecialchars($project['project_name']); ?>
                </div>
            </div>
        <?php else: ?>
            <!-- Project & Partner Context Card -->
            <div class="bg-slate-800/90 border border-slate-700 p-5 rounded-2xl space-y-3 shadow-lg">
                <div class="flex items-start justify-between gap-2">
                    <div>
                        <div class="text-[10px] font-bold text-indigo-400 uppercase tracking-wider"><?php echo htmlspecialchars($project['project_code']); ?></div>
                        <h1 class="text-lg font-bold text-white"><?php echo htmlspecialchars($project['project_name']); ?></h1>
                        <p class="text-xs text-slate-400 mt-0.5"><?php echo htmlspecialchars($project['site_address'] ?: 'Building Site'); ?></p>
                    </div>
                    <span class="text-[10px] font-bold px-2 py-0.5 rounded bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
                        <?php echo htmlspecialchars($artifact['type']); ?>
                    </span>
                </div>

                <div class="p-3 bg-slate-900/90 rounded-xl border border-slate-700/80 text-xs flex items-center justify-between">
                    <div>
                        <span class="text-slate-400 text-[10px] block">Assigned Contractor:</span>
                        <span class="font-bold text-white"><?php echo htmlspecialchars($partner['person_name']); ?></span>
                        <span class="text-indigo-400 text-[11px] block"><?php echo htmlspecialchars($partner['company_name']); ?></span>
                    </div>
                    <div class="text-right text-[11px] text-slate-400">
                        <span>Checklist:</span>
                        <div class="font-bold text-slate-200"><?php echo htmlspecialchars($artifact['title']); ?></div>
                    </div>
                </div>
            </div>

            <!-- Inspection Execution Form -->
            <form id="partner-form" action="partner_access.php?token=<?php echo urlencode($token); ?>" method="POST" enctype="multipart/form-data" class="bg-slate-800/90 border border-slate-700 p-6 rounded-2xl space-y-6 shadow-xl">
                <input type="hidden" name="action" value="submit_artifact">
                <input type="hidden" name="signature_data" id="partner-signature-input" value="">

                <div class="border-b border-slate-700 pb-3">
                    <h2 class="text-sm font-bold text-white uppercase tracking-wider">QC Checklist Questions</h2>
                    <p class="text-xs text-slate-400 mt-0.5">Please review and complete all required questions on site.</p>
                </div>

                <div class="space-y-4">
                    <?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'] ?? '');
                        
                        $opts = [];
                        if (!empty($f['options_json'])) {
                            $opts = json_decode($f['options_json'], true) ?: [];
                        }

                        // Robust type inference for photos, choices, or signatures
                        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']);
                    ?>
                        <div class="p-4 bg-slate-900/70 border border-slate-700 rounded-xl space-y-2.5">
                            <div class="flex items-center justify-between gap-2">
                                <label class="block text-xs font-bold text-slate-200">
                                    <?php echo ($index + 1); ?>. <?php echo htmlspecialchars($f['field_label']); ?>
                                    <?php if ($f['is_required']): ?><span class="text-rose-400 font-bold">*</span><?php endif; ?>
                                </label>
                                <span class="text-[9px] font-semibold px-2 py-0.5 rounded <?php echo $is_photo_type ? 'bg-indigo-500/20 text-indigo-300 border border-indigo-500/40' : 'bg-slate-800 text-slate-400 border border-slate-700'; ?> 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>

                            <?php if (!empty($f['help_text'])): ?>
                                <p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($f['help_text']); ?></p>
                            <?php endif; ?>

                            <?php if ($f_type === 'SINGLE_CHOICE'): 
                                $choice_list = !empty($opts) ? $opts : ['Pass', 'Fail', 'N/A'];
                            ?>
                                <div class="grid grid-cols-2 sm:grid-cols-3 gap-2 pt-1">
                                    <?php foreach ($choice_list as $opt): 
                                        $opt_lower = strtolower($opt);
                                        $is_pass = strpos($opt_lower, 'pass') !== false;
                                        $is_fail = strpos($opt_lower, 'fail') !== false;
                                    ?>
                                        <label class="flex items-center gap-2 p-2.5 rounded-xl bg-slate-800 border border-slate-700 text-xs text-slate-200 cursor-pointer hover:border-indigo-500 transition-colors">
                                            <input type="radio" name="field_<?php echo $f_id; ?>" value="<?php echo htmlspecialchars($opt); ?>" class="text-indigo-500 focus:ring-indigo-400" <?php echo $f['is_required'] ? 'required' : ''; ?>>
                                            <span class="<?php echo $is_pass ? 'text-emerald-400 font-bold' : ($is_fail ? 'text-rose-400 font-bold' : ''); ?>"><?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 gap-2 pt-1">
                                    <?php foreach ($choice_list as $opt): ?>
                                        <label class="flex items-center gap-2 p-2.5 rounded-xl bg-slate-800 border border-slate-700 text-xs text-slate-200 cursor-pointer hover:border-indigo-500 transition-colors">
                                            <input type="checkbox" name="field_<?php echo $f_id; ?>[]" value="<?php echo htmlspecialchars($opt); ?>" class="rounded text-indigo-500 focus:ring-indigo-400">
                                            <span><?php echo htmlspecialchars($opt); ?></span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>

                            <?php elseif ($f_type === 'DROPDOWN'): ?>
                                <select name="field_<?php echo $f_id; ?>" <?php echo $f['is_required'] ? 'required' : ''; ?> class="w-full px-3 py-2 bg-slate-800 border border-slate-600 rounded-xl text-xs text-white outline-none focus:border-indigo-500">
                                    <option value="">-- Choose Option --</option>
                                    <?php foreach ($opts as $opt): ?>
                                        <option value="<?php echo htmlspecialchars($opt); ?>"><?php echo htmlspecialchars($opt); ?></option>
                                    <?php endforeach; ?>
                                </select>

                            <?php elseif ($f_type === 'TEXT'): ?>
                                <input type="text" name="field_<?php echo $f_id; ?>" placeholder="Enter metric or response..." <?php echo $f['is_required'] ? 'required' : ''; ?> class="w-full px-3.5 py-2.5 bg-slate-800 border border-slate-600 rounded-xl text-xs text-white outline-none focus:border-indigo-500">

                            <?php elseif ($f_type === 'TEXTAREA'): ?>
                                <textarea name="field_<?php echo $f_id; ?>" rows="3" placeholder="Enter notes or observations..." <?php echo $f['is_required'] ? 'required' : ''; ?> class="w-full px-3.5 py-2.5 bg-slate-800 border border-slate-600 rounded-xl text-xs text-white outline-none focus:border-indigo-500"></textarea>

                            <?php elseif ($f_type === 'CHECKBOX'): ?>
                                <label class="flex items-center gap-2.5 p-3 rounded-xl bg-slate-800 border border-slate-700 text-xs text-slate-200 cursor-pointer">
                                    <input type="checkbox" name="field_<?php echo $f_id; ?>" value="1" <?php echo $f['is_required'] ? 'required' : ''; ?> class="w-4 h-4 rounded text-indigo-500">
                                    <span>Confirmed verified and compliant on site</span>
                                </label>

                            <?php elseif ($is_photo_type): ?>
                                <div class="space-y-3" id="photo-field-wrap-<?php echo $f_id; ?>">
                                    <div class="relative border-2 border-dashed border-slate-700 hover:border-indigo-400 bg-slate-800/80 rounded-2xl p-5 text-center transition-all cursor-pointer group">
                                        <input type="file" 
                                               id="partner-file-<?php echo $f_id; ?>" 
                                               name="photos_field_<?php echo $f_id; ?>[]" 
                                               multiple 
                                               accept="image/*,application/pdf" 
                                               capture="environment" 
                                               onchange="handlePartnerPhotoPreview(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-11 h-11 rounded-2xl bg-indigo-500/20 text-indigo-400 flex items-center justify-center mb-1.5 group-hover:scale-110 transition-all">
                                                <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-white block">Tap to Open Camera or Choose Photo</span>
                                            <span class="text-[11px] text-slate-400 block mt-0.5">Supports Mobile Camera • JPG, PNG, WEBP, PDF (Max 10MB)</span>
                                            <div class="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-indigo-600 text-white text-xs font-semibold">
                                                <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>Take / Attach Photo</span>
                                            </div>
                                        </div>
                                    </div>

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

                                    <!-- Optional Notes / Caption -->
                                    <input type="text" name="field_<?php echo $f_id; ?>" placeholder="Optional notes or photo caption..." class="w-full px-3.5 py-2 bg-slate-800 border border-slate-700 rounded-xl text-xs text-white outline-none focus:border-indigo-500">
                                </div>

                            <?php elseif ($f_type === 'SIGNATURE'): ?>
                                <div class="p-3 bg-slate-800/80 rounded-xl border border-slate-700 text-xs text-slate-400">
                                    Digital signature will be captured in the verification box below.
                                </div>
                            <?php else: ?>
                                <input type="text" name="field_<?php echo $f_id; ?>" placeholder="Enter observation..." class="w-full px-3.5 py-2.5 bg-slate-800 border border-slate-600 rounded-xl text-xs text-white outline-none focus:border-indigo-500">
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Sign-Off & Canvas Section -->
                <div class="p-5 bg-slate-900 border border-indigo-500/40 rounded-2xl space-y-4">
                    <div class="flex items-center justify-between">
                        <h3 class="text-xs font-bold text-indigo-300 uppercase tracking-wider">Contractor Sign-Off & Verification</h3>
                        <button type="button" onclick="clearPartnerSignature()" class="text-[11px] text-rose-400 hover:text-rose-300">Clear Signature</button>
                    </div>

                    <div>
                        <label class="block text-[11px] font-semibold text-slate-300 mb-1">Inspector / Sign-Off Full Name *</label>
                        <input type="text" name="completed_by_name" required value="<?php echo htmlspecialchars($partner['person_name']); ?>" class="w-full px-3.5 py-2.5 bg-slate-800 border border-slate-600 rounded-xl text-xs text-white outline-none focus:border-indigo-500">
                    </div>

                    <div>
                        <label class="block text-[11px] font-semibold text-slate-300 mb-1">Touch / Mouse Signature *</label>
                        <canvas id="partner-signature-pad" width="500" height="120" class="w-full h-32 bg-slate-800 rounded-xl border border-slate-600 touch-none cursor-crosshair"></canvas>
                    </div>
                </div>

                <button type="button" onclick="submitPartnerForm()" class="w-full py-3.5 bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs rounded-xl transition-all shadow-lg">
                    Submit Completed On-Site QC Sign-Off
                </button>
            </form>

            <script>
                const pCanvas = document.getElementById('partner-signature-pad');
                const pCtx = pCanvas ? pCanvas.getContext('2d') : null;
                let pDrawing = false;
                let pSigned = false;

                if (pCanvas && pCtx) {
                    function resizePartnerCanvas() {
                        const rect = pCanvas.getBoundingClientRect();
                        pCanvas.width = rect.width;
                        pCanvas.height = rect.height;
                        pCtx.strokeStyle = '#ffffff';
                        pCtx.lineWidth = 2.5;
                        pCtx.lineCap = 'round';
                        pCtx.lineJoin = 'round';
                    }
                    window.addEventListener('resize', resizePartnerCanvas);
                    resizePartnerCanvas();

                    function getPPos(e) {
                        const rect = pCanvas.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 };
                    }

                    pCanvas.addEventListener('mousedown', (e) => {
                        pDrawing = true; pSigned = true;
                        const pos = getPPos(e);
                        pCtx.beginPath(); pCtx.moveTo(pos.x, pos.y);
                    });
                    pCanvas.addEventListener('mousemove', (e) => {
                        if (!pDrawing) return;
                        const pos = getPPos(e);
                        pCtx.lineTo(pos.x, pos.y); pCtx.stroke();
                    });
                    pCanvas.addEventListener('mouseup', () => { pDrawing = false; });
                    pCanvas.addEventListener('mouseleave', () => { pDrawing = false; });

                    pCanvas.addEventListener('touchstart', (e) => {
                        pDrawing = true; pSigned = true;
                        const pos = getPPos(e);
                        pCtx.beginPath(); pCtx.moveTo(pos.x, pos.y);
                        if (e.cancelable) e.preventDefault();
                    }, { passive: false });
                    pCanvas.addEventListener('touchmove', (e) => {
                        if (!pDrawing) return;
                        const pos = getPPos(e);
                        pCtx.lineTo(pos.x, pos.y); pCtx.stroke();
                        if (e.cancelable) e.preventDefault();
                    }, { passive: false });
                    pCanvas.addEventListener('touchend', () => { pDrawing = false; });
                }

                function handlePartnerPhotoPreview(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-700 bg-slate-800 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-900 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-400 font-mono">📄 PDF</span>';
                            }
                            
                            const metaEl = document.createElement('div');
                            metaEl.className = 'px-1 text-[10px] truncate text-slate-200 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 clearPartnerSignature() {
                    if (pCtx && pCanvas) {
                        pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
                        pSigned = false;
                        document.getElementById('partner-signature-input').value = '';
                    }
                }

                function submitPartnerForm() {
                    if (pSigned && pCanvas) {
                        document.getElementById('partner-signature-input').value = pCanvas.toDataURL('image/png');
                    }
                    document.getElementById('partner-form').submit();
                }
            </script>
        <?php endif; ?>

        <div class="text-center text-[10px] text-slate-500">
            Powered by MiBuildqc Quality Control System
        </div>

    </div>

</body>
</html>