<?php
/**
 * Project Details & Quality Control Artifacts Manager
 * Location: public_html/team/project_details.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';

$project_id = $_GET['id'] ?? '';
if (empty($project_id)) {
    header("Location: dashboard.php");
    exit;
}

$action_success = '';
$action_error = '';

// ==========================================
// 1. QUERY COMPANY NAME & PRIMARY OWNER
// ==========================================
$company_name = $_SESSION['company_name'] ?? 'Company Name';
$primary_owner_name = ($_SESSION['first_name'] ?? '') . ' ' . ($_SESSION['last_name'] ?? '');

try {
    $stmt_acc = $pdo->prepare("
        SELECT a.company_name, u.first_name, u.last_name 
        FROM accounts a 
        LEFT JOIN users u ON a.id = u.account_id AND u.role = 'PRIMARY_ADMIN' 
        WHERE a.id = ? 
        ORDER BY u.created_at ASC 
        LIMIT 1
    ");
    $stmt_acc->execute([$account_id]);
    $account_info = $stmt_acc->fetch();
    if ($account_info) {
        if (!empty($account_info['company_name'])) {
            $company_name = $account_info['company_name'];
        }
        if (!empty($account_info['first_name'])) {
            $primary_owner_name = trim($account_info['first_name'] . ' ' . $account_info['last_name']);
        }
    }
} catch (Exception $e) {
    // Session fallback
}

// ==========================================
// 2. HANDLE POST ACTIONS
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Action A: Close Project
    if ($action === 'close_project') {
        try {
            $stmt_close = $pdo->prepare("
                UPDATE projects 
                SET status = 'CLOSED', closed_at = NOW(), closed_by_user_id = ? 
                WHERE id = ? AND account_id = ?
            ");
            $stmt_close->execute([$user_id, $project_id, $account_id]);

            // Log action
            $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'PROJECT_CLOSED', ?)");
            $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Closed project ID: $project_id"]);

            $action_success = "Project has been closed and archived.";
        } catch (Exception $e) {
            $action_error = "Error closing project: " . $e->getMessage();
        }
    }

    // Action B: Attach QC Artifact
    elseif ($action === 'attach_artifact') {
        $template_id = trim($_POST['template_id'] ?? '');
        $assigned_partner_id = trim($_POST['assigned_partner_id'] ?? '');
        if (empty($assigned_partner_id)) {
            $assigned_partner_id = null;
        }

        if (empty($template_id)) {
            $action_error = "Please select an artifact template.";
        } else {
            try {
                // Fetch template metadata
                $stmt_tmpl = $pdo->prepare("SELECT * FROM artifact_templates WHERE id = ? AND (account_id = ? OR account_id IS NULL)");
                $stmt_tmpl->execute([$template_id, $account_id]);
                $template = $stmt_tmpl->fetch();

                if (!$template) {
                    $action_error = "Selected artifact template not found.";
                } else {
                    $art_id = 'art_' . bin2hex(random_bytes(6));
                    $initial_status = $assigned_partner_id ? 'SENT_TO_PARTNER' : 'DRAFT';

                    $stmt_ins = $pdo->prepare("
                        INSERT INTO project_artifacts (id, project_id, template_id, title, type, assigned_partner_id, status) 
                        VALUES (?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt_ins->execute([
                        $art_id,
                        $project_id,
                        $template['id'],
                        $template['title'],
                        $template['type'],
                        $assigned_partner_id,
                        $initial_status
                    ]);

                    // If assigned to a partner, generate a secure temporary access token
                    if ($assigned_partner_id) {
                        $link_id = 'lnk_' . bin2hex(random_bytes(6));
                        $token = bin2hex(random_bytes(24));
                        $expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));

                        $stmt_lnk = $pdo->prepare("
                            INSERT INTO partner_access_links (id, project_artifact_id, partner_id, token, expires_at, is_active)
                            VALUES (?, ?, ?, ?, ?, 1)
                        ");
                        $stmt_lnk->execute([$link_id, $art_id, $assigned_partner_id, $token, $expires_at]);
                    }

                    $action_success = "QC Artifact <strong>" . htmlspecialchars($template['title']) . "</strong> attached to project successfully!";
                }
            } catch (Exception $e) {
                $action_error = "Error attaching artifact: " . $e->getMessage();
            }
        }
    }

    // Action C: Generate / Regenerate Execution Link for Partner
    elseif ($action === 'generate_link') {
        $artifact_id = trim($_POST['artifact_id'] ?? '');
        $partner_id = trim($_POST['partner_id'] ?? '');

        if (!empty($artifact_id) && !empty($partner_id)) {
            try {
                // Update artifact assignment
                $stmt_upd = $pdo->prepare("UPDATE project_artifacts SET assigned_partner_id = ?, status = 'SENT_TO_PARTNER' WHERE id = ? AND project_id = ?");
                $stmt_upd->execute([$partner_id, $artifact_id, $project_id]);

                // Create fresh token
                $link_id = 'lnk_' . bin2hex(random_bytes(6));
                $token = bin2hex(random_bytes(24));
                $expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));

                $stmt_lnk = $pdo->prepare("
                    INSERT INTO partner_access_links (id, project_artifact_id, partner_id, token, expires_at, is_active)
                    VALUES (?, ?, ?, ?, ?, 1)
                ");
                $stmt_lnk->execute([$link_id, $artifact_id, $partner_id, $token, $expires_at]);

                $action_success = "New secure partner execution token generated.";
            } catch (Exception $e) {
                $action_error = "Error generating partner link: " . $e->getMessage();
            }
        }
    }
}

// ==========================================
// 3. FETCH PROJECT DETAILS & VERIFY ACCESS
// ==========================================
$stmt_p = $pdo->prepare("SELECT * FROM projects WHERE id = ? AND account_id = ?");
$stmt_p->execute([$project_id, $account_id]);
$project = $stmt_p->fetch();

if (!$project) {
    die("<div style='font-family:sans-serif;padding:30px;text-align:center;'><h2>Project not found or access denied.</h2><p><a href='dashboard.php'>&larr; Return to Dashboard</a></p></div>");
}

$is_closed = ($project['status'] === 'CLOSED');

// ==========================================
// 4. FETCH PROJECT ARTIFACTS & DETAILS
// ==========================================
$stmt_arts = $pdo->prepare("
    SELECT pa.*, 
           ep.person_name as partner_person_name, 
           ep.company_name as partner_company_name, 
           ep.email as partner_email,
           (SELECT COUNT(*) FROM artifact_files af WHERE af.project_artifact_id = pa.id) as files_count,
           (SELECT token FROM partner_access_links pal WHERE pal.project_artifact_id = pa.id AND pal.is_active = 1 ORDER BY pal.created_at DESC LIMIT 1) as active_token
    FROM project_artifacts pa 
    LEFT JOIN external_partners ep ON pa.assigned_partner_id = ep.id 
    WHERE pa.project_id = ? 
    ORDER BY pa.created_at DESC
");
$stmt_arts->execute([$project_id]);
$artifacts = $stmt_arts->fetchAll();

$total_artifacts = count($artifacts);
$completed_artifacts = count(array_filter($artifacts, fn($a) => ($a['status'] ?? '') === 'COMPLETED'));
$completion_pct = $total_artifacts > 0 ? round(($completed_artifacts / $total_artifacts) * 100) : 0;

// ==========================================
// 5. FETCH TEMPLATES & PARTNERS FOR MODALS
// ==========================================
$stmt_tmpls = $pdo->prepare("SELECT * FROM artifact_templates WHERE (account_id = ? OR account_id IS NULL) ORDER BY category ASC, title ASC");
$stmt_tmpls->execute([$account_id]);
$templates = $stmt_tmpls->fetchAll();

$stmt_parts = $pdo->prepare("SELECT * FROM external_partners WHERE account_id = ? ORDER BY company_name ASC, person_name ASC");
$stmt_parts->execute([$account_id]);
$partners = $stmt_parts->fetchAll();

// Base URL for generating partner token links
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$base_domain = $protocol . $_SERVER['HTTP_HOST'];
$exec_base_url = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/\\') . '/partner_exec.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($project['project_name']); ?> (<?php echo htmlspecialchars($project['project_code']); ?>) - MiBuildqc</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <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-200 min-h-screen text-slate-800">

    <?php require_once("../includes/layout-header.php") ;?>

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

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

        <!-- Back Button & Status Actions Header -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <a href="dashboard.php" class="inline-flex items-center gap-2 text-sm font-semibold text-slate-600 hover:text-slate-900 transition-colors">
                <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>Back to Projects List</span>
            </a>

            <div class="flex items-center gap-3">
                <?php if (!$is_closed): ?>
                    <form action="project_details.php?id=<?php echo urlencode($project_id); ?>" method="POST" onsubmit="return confirm('Are you sure you want to close and archive this project?');">
                        <input type="hidden" name="action" value="close_project">
                        <button type="submit" class="px-3.5 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-300 font-medium text-xs transition-all flex items-center gap-1.5 shadow-xs">
                            <svg class="w-3.5 h-3.5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
                            <span>Close Project</span>
                        </button>
                    </form>
                <?php else: ?>
                    <span class="px-3.5 py-1.5 rounded-full bg-slate-200 text-slate-700 font-semibold text-xs border border-slate-300 flex items-center gap-1.5">
                        <svg class="w-3.5 h-3.5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
                        Project Closed & Archived
                    </span>
                <?php endif; ?>

                <a href="artifact-template-builder.php?project_id=<?php echo urlencode($project_id); ?>" class="px-3.5 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs transition-all flex items-center gap-1.5 border border-slate-200 shadow-2xs">
                    <svg class="w-3.5 h-3.5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path></svg>
                    <span>Template Builder</span>
                </a>

                <button onclick="document.getElementById('attach-artifact-modal').classList.remove('hidden')" <?php echo $is_closed ? 'disabled' : ''; ?> class="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white font-medium text-sm transition-all shadow-xs 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="M9 13h6m-3-3v6m5 5H7a2 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>Attach QC Artifact</span>
                </button>
            </div>
        </div>

        <!-- Project Banner & Metadata Summary -->
        <div class="bg-white rounded-2xl border border-slate-200 p-6 shadow-xs space-y-6">
            <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-6 border-b border-slate-100 pb-6">
                <div class="space-y-2">
                    <div class="flex items-center gap-2">
                        <span class="font-mono text-xs font-bold px-2.5 py-1 bg-indigo-50 text-indigo-700 border border-indigo-200 rounded-md">
                            <?php echo htmlspecialchars($project['project_code']); ?>
                        </span>
                        <span class="px-2.5 py-0.5 rounded-full text-xs font-semibold border <?php echo $is_closed ? 'bg-slate-100 text-slate-600 border-slate-200' : 'bg-emerald-50 text-emerald-700 border-emerald-200'; ?>">
                            ● <?php echo $is_closed ? 'Closed' : 'Active Site'; ?>
                        </span>
                        <span class="px-2 py-0.5 rounded text-[10px] font-medium bg-slate-100 text-slate-600">
                            Access: <?php echo htmlspecialchars($project['access_level']); ?>
                        </span>
                    </div>
                    <h1 class="text-2xl sm:text-3xl font-bold text-slate-900 tracking-tight">
                        <?php echo htmlspecialchars($project['project_name']); ?>
                    </h1>
                    <div class="text-xs text-slate-500 flex items-center gap-1.5">
                        <svg class="w-3.5 h-3.5 text-slate-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path></svg>
                        <span><?php echo htmlspecialchars($project['address']); ?></span>
                    </div>
                </div>

                <!-- QC Completion Rate Progress Gauge -->
                <div class="p-4 rounded-xl bg-slate-50 border border-slate-200/80 shrink-0 space-y-2 text-right min-w-[200px]">
                    <div class="text-xs text-slate-500 uppercase font-semibold">QC Completion Rate</div>
                    <div class="text-2xl font-bold text-slate-900">
                        <?php echo $completed_artifacts; ?> / <?php echo $total_artifacts; ?> <span class="text-xs font-normal text-slate-500">Completed</span>
                    </div>
                    <div class="w-48 h-2 bg-slate-200 rounded-full overflow-hidden ml-auto">
                        <div class="h-full bg-indigo-600 transition-all duration-300" style="width: <?php echo $completion_pct; ?>%"></div>
                    </div>
                </div>
            </div>

            <!-- Client Contact Details -->
            <div class="grid sm:grid-cols-3 gap-4 text-xs">
                <div class="p-3.5 rounded-xl bg-slate-50/70 border border-slate-100 space-y-1">
                    <div class="text-slate-400 uppercase font-semibold text-[10px]">Client Name</div>
                    <div class="font-bold text-slate-800 flex items-center gap-1.5">
                        <svg class="w-3.5 h-3.5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                        <?php echo htmlspecialchars($project['client_name']); ?>
                    </div>
                </div>

                <div class="p-3.5 rounded-xl bg-slate-50/70 border border-slate-100 space-y-1">
                    <div class="text-slate-400 uppercase font-semibold text-[10px]">Client Email</div>
                    <div class="font-medium text-slate-700 flex items-center gap-1.5">
                        <svg class="w-3.5 h-3.5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                        <?php echo htmlspecialchars($project['client_email'] ?: 'N/A'); ?>
                    </div>
                </div>

                <div class="p-3.5 rounded-xl bg-slate-50/70 border border-slate-100 space-y-1">
                    <div class="text-slate-400 uppercase font-semibold text-[10px]">Client Mobile</div>
                    <div class="font-medium text-slate-700 flex items-center gap-1.5">
                        <svg class="w-3.5 h-3.5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path></svg>
                        <?php echo htmlspecialchars($project['client_mobile'] ?: 'N/A'); ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- ==================== LINKED ARTIFACTS LIST ==================== -->
        <div class="space-y-4">
            <div class="flex items-center justify-between px-1">
                <h3 class="text-base font-bold text-slate-900 flex items-center gap-2">
                    <svg class="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    Project Quality Control Artifacts (<?php echo $total_artifacts; ?>)
                </h3>
                <span class="text-xs text-slate-500">
                    Checklists, questionnaires, reviews, and compliance documents
                </span>
            </div>

            <?php if (empty($artifacts)): ?>
                <div class="text-center py-12 bg-white rounded-2xl border border-dashed border-slate-300 p-8 space-y-3">
                    <svg class="w-10 h-10 text-slate-300 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 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>
                    <h4 class="text-sm font-semibold text-slate-800">No artifacts attached to this project yet</h4>
                    <p class="text-xs text-slate-500 max-w-md mx-auto">
                        Attach a standard QC checklist or custom questionnaire to assign it to a subcontractor or execute it on site.
                    </p>
                    <div class="flex items-center justify-center gap-2 pt-1 flex-wrap">
                        <button onclick="document.getElementById('attach-artifact-modal').classList.remove('hidden')" <?php echo $is_closed ? 'disabled' : ''; ?> class="px-4 py-2 rounded-xl bg-indigo-600 text-white text-xs font-semibold hover:bg-indigo-700 transition-all inline-flex items-center gap-1.5 shadow-xs">
                            + Attach First Artifact
                        </button>
                        <a href="artifact-template-builder.php?project_id=<?php echo urlencode($project_id); ?>" class="px-4 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold border border-slate-200 inline-flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path></svg>
                            Build Custom Template
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <div class="space-y-3">
                    <?php foreach ($artifacts as $art): 
                        $art_completed = ($art['status'] === 'COMPLETED');
                        $token_url = $art['active_token'] ? "{$base_domain}{$exec_base_url}?token=" . urlencode($art['active_token']) : '';
                    ?>
                        <div class="bg-white border border-slate-200/90 rounded-2xl p-5 shadow-xs hover:border-slate-300 transition-all flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                            <div class="space-y-2 flex-1">
                                <div class="flex items-center gap-2 flex-wrap">
                                    <span class="text-[11px] font-bold px-2.5 py-0.5 rounded bg-slate-100 text-slate-700 border border-slate-200">
                                        <?php echo str_replace('_', ' ', htmlspecialchars($art['type'])); ?>
                                    </span>

                                    <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold border <?php 
                                        if ($art_completed) echo 'bg-emerald-50 text-emerald-700 border-emerald-200';
                                        elseif ($art['status'] === 'SENT_TO_PARTNER') echo 'bg-amber-50 text-amber-800 border-amber-200';
                                        else echo 'bg-slate-100 text-slate-700 border-slate-200';
                                    ?>">
                                        ● <?php 
                                            if ($art_completed) echo 'Completed';
                                            elseif ($art['status'] === 'SENT_TO_PARTNER') echo 'Sent for Execution';
                                            else echo 'In Progress';
                                        ?>
                                    </span>
                                </div>

                                <h4 class="text-base font-bold text-slate-900"><?php echo htmlspecialchars($art['title']); ?></h4>

                                <div class="flex items-center gap-4 text-xs text-slate-500 flex-wrap">
                                    <?php if (!empty($art['partner_person_name'])): ?>
                                        <span class="flex items-center gap-1 text-slate-700 font-medium">
                                            <svg class="w-3.5 h-3.5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path></svg>
                                            Partner: <?php echo htmlspecialchars($art['partner_person_name']); ?> (<?php echo htmlspecialchars($art['partner_company_name']); ?>)
                                        </span>
                                    <?php else: ?>
                                        <span class="text-slate-400">Assigned: Internal Team</span>
                                    <?php endif; ?>

                                    <?php if ($art_completed && !empty($art['completed_by_name'])): ?>
                                        <span class="text-emerald-700 flex items-center gap-1 font-medium">
                                            <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="M5 13l4 4L19 7"></path></svg>
                                            Signed by <?php echo htmlspecialchars($art['completed_by_name']); ?> on <?php echo date('M d, Y', strtotime($art['completed_at'])); ?>
                                        </span>
                                    <?php endif; ?>

                                    <?php if ($art['files_count'] > 0): ?>
                                        <span class="flex items-center gap-1 text-slate-600 font-medium">
                                            <svg class="w-3.5 h-3.5 text-indigo-500" 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>
                                            <?php echo $art['files_count']; ?> Photo/Doc Attachments
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="flex items-center gap-2 w-full md:w-auto shrink-0 pt-2 md:pt-0 border-t md:border-t-0 border-slate-100">
                                <?php if (!$art_completed && !$is_closed): ?>
                                    <?php if ($token_url): ?>
                                        <button onclick="copyToClipboard('<?php echo htmlspecialchars($token_url); ?>', this)" class="px-3 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold transition-all flex items-center gap-1.5 border border-slate-200" title="Copy Temporary Partner Token Link">
                                            <svg class="w-3.5 h-3.5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"></path></svg>
                                            <span>Copy Link</span>
                                        </button>
                                    <?php else: ?>
                                        <button onclick="openGenerateModal('<?php echo $art['id']; ?>', '<?php echo htmlspecialchars(addslashes($art['title'])); ?>')" class="px-3 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold transition-all flex items-center gap-1.5 border border-slate-200">
                                            <svg class="w-3.5 h-3.5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path></svg>
                                            <span>Generate Link</span>
                                        </button>
                                    <?php endif; ?>
                                <?php endif; ?>

                                <!-- Execute on Site / Review Answers -->
                                <a href="artifact_executor.php?artifact_id=<?php echo urlencode($art['id']); ?>" class="px-3.5 py-2 rounded-xl text-xs font-semibold transition-all flex items-center gap-1.5 border <?php echo $art_completed ? 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50' : 'bg-indigo-600 hover:bg-indigo-700 text-white border-indigo-600 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                                    <span><?php echo $art_completed ? 'Review Answers' : 'Execute on Site'; ?></span>
                                </a>

                                <!-- PDF Report Button -->
                                <a href="artifact_pdf.php?artifact_id=<?php echo urlencode($art['id']); ?>" target="_blank" class="px-3.5 py-2 rounded-xl bg-slate-900 hover:bg-slate-800 text-white text-xs font-semibold transition-all flex items-center gap-1.5 shadow-xs">
                                    <svg class="w-3.5 h-3.5 text-indigo-400" 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>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

    </main>

    <!-- ==================== ATTACH ARTIFACT MODAL ==================== -->
    <div id="attach-artifact-modal" class="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-2xl max-w-lg w-full p-6 shadow-2xl border border-slate-200 space-y-5">
            <div class="flex items-center justify-between border-b border-slate-100 pb-4">
                <h3 class="text-lg font-bold text-slate-900">Attach Artifact to Project</h3>
                <button onclick="document.getElementById('attach-artifact-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600 font-bold text-sm">✕</button>
            </div>

            <form action="project_details.php?id=<?php echo urlencode($project_id); ?>" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="attach_artifact">

                <div>
                    <div class="flex items-center justify-between mb-1">
                        <label class="block text-xs font-semibold text-slate-700">Select Artifact Template *</label>
                        <a href="artifact-template-builder.php?project_id=<?php echo urlencode($project_id); ?>" class="text-[11px] text-indigo-600 hover:text-indigo-800 font-semibold inline-flex items-center gap-1 hover:underline">
                            Create / Customize in Builder &rarr;
                        </a>
                    </div>
                    <select name="template_id" required class="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                        <?php foreach ($templates as $tmpl): ?>
                            <option value="<?php echo htmlspecialchars($tmpl['id']); ?>">
                                <?php echo htmlspecialchars($tmpl['title']); ?> (<?php echo htmlspecialchars($tmpl['category']); ?> - <?php echo str_replace('_', ' ', htmlspecialchars($tmpl['type'])); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-700 mb-1">Assign to External Partner / Subcontractor</label>
                    <select name="assigned_partner_id" class="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                        <option value="">-- Assign Later / Internal Execution --</option>
                        <?php foreach ($partners as $p): ?>
                            <option value="<?php echo htmlspecialchars($p['id']); ?>">
                                <?php echo htmlspecialchars($p['person_name']); ?> - <?php echo htmlspecialchars($p['company_name']); ?> (<?php echo htmlspecialchars($p['email']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="text-[11px] text-slate-500 mt-1">
                        External partners receive a temporary web token link to execute on mobile without needing a permanent login.
                    </p>
                </div>

                <div class="flex items-center justify-end gap-3 pt-3 border-t border-slate-100">
                    <button type="button" onclick="document.getElementById('attach-artifact-modal').classList.add('hidden')" class="px-4 py-2 rounded-xl border border-slate-200 text-slate-600 text-sm hover:bg-slate-50">
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold shadow-xs">
                        Attach to Project
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ==================== GENERATE LINK MODAL ==================== -->
    <div id="generate-link-modal" class="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl border border-slate-200 space-y-4">
            <div class="flex items-center justify-between border-b border-slate-100 pb-3">
                <h3 class="text-base font-bold text-slate-900">Generate Partner Execution Link</h3>
                <button onclick="document.getElementById('generate-link-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600 font-bold text-sm">✕</button>
            </div>

            <form action="project_details.php?id=<?php echo urlencode($project_id); ?>" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="generate_link">
                <input type="hidden" name="artifact_id" id="gen-modal-artifact-id" value="">

                <div>
                    <div class="text-xs text-slate-500 mb-2">Artifact: <strong id="gen-modal-artifact-title" class="text-slate-800"></strong></div>
                    <label class="block text-xs font-semibold text-slate-700 mb-1">Select Subcontractor / Partner *</label>
                    <select name="partner_id" required class="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                        <?php foreach ($partners as $p): ?>
                            <option value="<?php echo htmlspecialchars($p['id']); ?>">
                                <?php echo htmlspecialchars($p['person_name']); ?> - <?php echo htmlspecialchars($p['company_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-100">
                    <button type="button" onclick="document.getElementById('generate-link-modal').classList.add('hidden')" class="px-4 py-2 border border-slate-200 rounded-xl text-xs font-semibold text-slate-600 hover:bg-slate-50">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs rounded-xl shadow-xs">Create Token & Link</button>
                </div>
            </form>
        </div>
    </div>

    <!-- JavaScript Helpers -->
    <script>
        function copyToClipboard(text, btnElement) {
            navigator.clipboard.writeText(text).then(() => {
                const originalHtml = btnElement.innerHTML;
                btnElement.innerHTML = `<svg class="w-3.5 h-3.5 text-emerald-600" 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 class="text-emerald-700 font-bold">Link Copied!</span>`;
                setTimeout(() => {
                    btnElement.innerHTML = originalHtml;
                }, 2500);
            }).catch(err => {
                alert('Could not copy link: ' + text);
            });
        }

        function openGenerateModal(artifactId, artifactTitle) {
            document.getElementById('gen-modal-artifact-id').value = artifactId;
            document.getElementById('gen-modal-artifact-title').innerText = artifactTitle;
            document.getElementById('generate-link-modal').classList.remove('hidden');
        }
    </script>

</body>
</html>