<?php
/**
 * External Partners & Subcontractors Directory
 * Location: public_html/team/partners.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';

$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: Create Partner
    if ($action === 'create_partner') {
        $person_name = trim($_POST['person_name'] ?? '');
        $partner_company = trim($_POST['company_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $mobile_number = trim($_POST['mobile_number'] ?? '');

        if (empty($person_name) || empty($partner_company) || empty($email)) {
            $action_error = "Contact Person Name, Subcontractor Company Name, and Email Address are required.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $action_error = "Please enter a valid email address.";
        } else {
            try {
                $partner_id = 'part_' . bin2hex(random_bytes(6));
                $stmt_ins = $pdo->prepare("
                    INSERT INTO external_partners (id, account_id, person_name, company_name, email, mobile_number) 
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $stmt_ins->execute([$partner_id, $account_id, $person_name, $partner_company, $email, $mobile_number]);

                // Audit log
                $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'PARTNER_CREATED', ?)");
                $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Added partner: $person_name ($partner_company)"]);

                $action_success = "Subcontractor partner <strong>" . htmlspecialchars($person_name) . " (" . htmlspecialchars($partner_company) . ")</strong> added successfully!";
            } catch (Exception $e) {
                $action_error = "Error creating partner: " . $e->getMessage();
            }
        }
    }

    // Action B: Edit Partner
    elseif ($action === 'edit_partner') {
        $partner_id = trim($_POST['partner_id'] ?? '');
        $person_name = trim($_POST['person_name'] ?? '');
        $partner_company = trim($_POST['company_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $mobile_number = trim($_POST['mobile_number'] ?? '');

        if (empty($partner_id) || empty($person_name) || empty($partner_company) || empty($email)) {
            $action_error = "All mandatory fields must be completed.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $action_error = "Please enter a valid email address.";
        } else {
            try {
                $stmt_upd = $pdo->prepare("
                    UPDATE external_partners 
                    SET person_name = ?, company_name = ?, email = ?, mobile_number = ? 
                    WHERE id = ? AND account_id = ?
                ");
                $stmt_upd->execute([$person_name, $partner_company, $email, $mobile_number, $partner_id, $account_id]);

                // Audit log
                $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'PARTNER_UPDATED', ?)");
                $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Updated partner: $person_name ($partner_company)"]);

                $action_success = "Partner details updated successfully!";
            } catch (Exception $e) {
                $action_error = "Error updating partner: " . $e->getMessage();
            }
        }
    }

    // Action C: Delete Partner
    elseif ($action === 'delete_partner') {
        $partner_id = trim($_POST['partner_id'] ?? '');
        try {
            // Nullify artifact references before deletion
            $stmt_null_arts = $pdo->prepare("UPDATE project_artifacts SET assigned_partner_id = NULL WHERE assigned_partner_id = ?");
            $stmt_null_arts->execute([$partner_id]);

            $stmt_del = $pdo->prepare("DELETE FROM external_partners WHERE id = ? AND account_id = ?");
            $stmt_del->execute([$partner_id, $account_id]);

            if ($stmt_del->rowCount() > 0) {
                // Audit log
                $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'PARTNER_DELETED', ?)");
                $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Deleted partner ID: $partner_id"]);

                $action_success = "Partner removed from directory.";
            } else {
                $action_error = "Partner not found or already removed.";
            }
        } catch (Exception $e) {
            $action_error = "Error deleting partner: " . $e->getMessage();
        }
    }

    // Action D: Generate & Dispatch Artifact Link
    elseif ($action === 'dispatch_link') {
        $partner_id = trim($_POST['partner_id'] ?? '');
        $project_artifact_id = trim($_POST['project_artifact_id'] ?? '');

        if (empty($partner_id) || empty($project_artifact_id)) {
            $action_error = "Both Partner and Target Project Artifact are required to generate an access link.";
        } else {
            try {
                // Verify artifact belongs to account and partner
                $stmt_chk = $pdo->prepare("
                    SELECT pa.id, pa.title, pa.status, p.project_code, p.project_name, ep.person_name, ep.company_name, ep.email, ep.mobile_number
                    FROM project_artifacts pa
                    JOIN projects p ON pa.project_id = p.id
                    JOIN external_partners ep ON ep.id = ?
                    WHERE pa.id = ? AND p.account_id = ? AND pa.assigned_partner_id = ?
                ");
                $stmt_chk->execute([$partner_id, $project_artifact_id, $account_id, $partner_id]);
                $link_target = $stmt_chk->fetch();

                if (!$link_target) {
                    $action_error = "Artifact not found or not assigned to this partner.";
                } else {
                    $token = 'tk_' . bin2hex(random_bytes(24));
                    $link_id = 'pal_' . bin2hex(random_bytes(6));
                    $expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));

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

                    // Update artifact status to SENT_TO_PARTNER if currently DRAFT
                    if ($link_target['status'] === 'DRAFT') {
                        $stmt_upd_art = $pdo->prepare("UPDATE project_artifacts SET status = 'SENT_TO_PARTNER' WHERE id = ?");
                        $stmt_upd_art->execute([$project_artifact_id]);
                    }

                    // Audit log
                    $stmt_log = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details) VALUES (?, ?, ?, 'PARTNER_LINK_GENERATED', ?)");
                    $stmt_log->execute(['log_' . bin2hex(random_bytes(6)), $account_id, $user_id, "Generated site link for '{$link_target['title']}' to {$link_target['person_name']}"]);

                    // Log mock SMS/Email
                    $base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
                    $access_url = "$base_url/partner_access.php?token=$token";
                    $log_entry = "[" . date('Y-m-d H:i:s') . "] SMS/EMAIL LINK DISPATCH | TO: {$link_target['email']} / {$link_target['mobile_number']} | ARTIFACT: {$link_target['title']} ({$link_target['project_code']}) | URL: $access_url
";
                    @file_put_contents(__DIR__ . '/../mail_debug.log', $log_entry, FILE_APPEND);

                    $action_success = "Site access link generated for <strong>" . htmlspecialchars($link_target['person_name']) . "</strong> on artifact <strong>" . htmlspecialchars($link_target['title']) . "</strong>! Link: <code class='bg-emerald-100 text-emerald-900 px-2 py-0.5 rounded font-mono text-[11px] select-all'>$access_url</code>";
                }
            } catch (Exception $e) {
                $action_error = "Error generating link: " . $e->getMessage();
            }
        }
    }
}

// ==========================================
// 3. FETCH PARTNERS & ASSIGNED ARTIFACTS
// ==========================================
try {
    $stmt_parts = $pdo->prepare("
        SELECT ep.*, 
               COUNT(DISTINCT pa.id) AS assigned_artifact_count,
               COUNT(DISTINCT pal.id) AS active_link_count
        FROM external_partners ep
        LEFT JOIN project_artifacts pa ON ep.id = pa.assigned_partner_id
        LEFT JOIN partner_access_links pal ON ep.id = pal.partner_id AND pal.is_active = 1
        WHERE ep.account_id = ?
        GROUP BY ep.id
        ORDER BY ep.created_at DESC
    ");
    $stmt_parts->execute([$account_id]);
    $partners = $stmt_parts->fetchAll();

    // Fetch assigned artifacts list for details
    $stmt_art_details = $pdo->prepare("
        SELECT pa.id, pa.title, pa.type, pa.status, pa.assigned_partner_id, p.id AS project_id, p.project_code, p.project_name 
        FROM project_artifacts pa 
        JOIN projects p ON pa.project_id = p.id 
        WHERE p.account_id = ? AND pa.assigned_partner_id IS NOT NULL
        ORDER BY pa.created_at DESC
    ");
    $stmt_art_details->execute([$account_id]);
    $assigned_arts_raw = $stmt_art_details->fetchAll();
    
    $partner_artifacts_map = [];
    foreach ($assigned_arts_raw as $art) {
        $partner_artifacts_map[$art['assigned_partner_id']][] = $art;
    }
} catch (Exception $e) {
    $partners = [];
    $partner_artifacts_map = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subcontractors & Partners Directory - <?php echo htmlspecialchars($company_name); ?></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/80 min-h-screen text-slate-800 antialiased flex flex-col">

    <?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 flex-1 w-full">

        <!-- Flash Alerts -->
        <?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; ?>

        <!-- Directory Header & Action Bar -->
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-slate-200 shadow-xs">
            <div class="space-y-1">
                <div class="flex items-center gap-2">
                    <h1 class="text-xl sm:text-2xl font-extrabold text-slate-900 tracking-tight">Subcontractors & Partners Directory</h1>
                    <span class="text-xs font-bold px-2.5 py-0.5 rounded-full bg-indigo-50 text-indigo-700 border border-indigo-200">
                        <?php echo count($partners); ?> Registered
                    </span>
                    <span class="text-xs font-semibold px-2.5 py-0.5 rounded-full bg-slate-100 text-slate-600 border border-slate-200">
                        Company-Wide & Project-Agnostic
                    </span>
                </div>
                <p class="text-xs text-slate-500 max-w-2xl">
                    Subcontractors are stored at the company level. You can assign them to checklists across any existing or future project to issue secure on-site mobile links.
                </p>
            </div>

            <button onclick="openCreateModal()" class="px-4 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-xs transition-all shadow-sm flex items-center gap-2 shrink-0">
                <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="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"></path></svg>
                <span>Add Subcontractor Partner</span>
            </button>
        </div>

        <!-- Search Bar -->
        <div class="bg-white rounded-2xl border border-slate-200 p-4 shadow-xs flex flex-col sm:flex-row items-center justify-between gap-4">
            <div class="relative w-full sm:max-w-md">
                <svg class="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                <input type="text" id="partner-search-input" onkeyup="searchPartners()" placeholder="Search by contact name, subcontractor company, email, phone..." class="w-full pl-10 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 focus:bg-white outline-none transition-all">
            </div>

            <div class="text-xs text-slate-500 font-medium">
                Showing <strong id="partner-visible-count"><?php echo count($partners); ?></strong> partner<?php echo count($partners) === 1 ? '' : 's'; ?>
            </div>
        </div>

        <!-- Partner Cards Grid -->
        <?php if (empty($partners)): ?>
            <div class="text-center py-16 bg-white rounded-2xl border border-slate-200 p-8 space-y-4 shadow-xs">
                <div class="w-14 h-14 rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center mx-auto shadow-2xs">
                    <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
                </div>
                <div>
                    <h3 class="text-base font-bold text-slate-900">No external partners registered yet</h3>
                    <p class="text-xs text-slate-500 mt-1 max-w-md mx-auto">
                        Add trade subcontractors, certifiers, or field engineers to assign them QC checklists and generate passwordless site access links.
                    </p>
                </div>
                <button onclick="openCreateModal()" class="px-4 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-xs transition-all shadow-xs inline-flex items-center gap-1.5">
                    <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="M12 4v16m8-8H4"></path></svg>
                    <span>Add First Partner</span>
                </button>
            </div>
        <?php else: ?>
            <div id="partners-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php foreach ($partners as $p): 
                    $assigned_arts = $partner_artifacts_map[$p['id']] ?? [];
                    $art_count = count($assigned_arts);
                ?>
                    <div class="partner-card bg-white rounded-2xl border border-slate-200 p-5 shadow-xs hover:border-indigo-300 transition-all flex flex-col justify-between space-y-4"
                         data-search="<?php echo htmlspecialchars(strtolower($p['person_name'] . ' ' . $p['company_name'] . ' ' . $p['email'] . ' ' . ($p['mobile_number'] ?? ''))); ?>">
                        
                        <div class="space-y-3.5">
                            <div class="flex items-center justify-between gap-2">
                                <div class="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-700 border border-indigo-100 flex items-center justify-center font-bold text-sm shadow-2xs">
                                    <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="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>
                                </div>
                                <span class="text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200">
                                    Active Subcontractor
                                </span>
                            </div>

                            <div>
                                <h3 class="text-base font-bold text-slate-900 leading-snug"><?php echo htmlspecialchars($p['person_name']); ?></h3>
                                <p class="text-xs font-semibold text-indigo-600"><?php echo htmlspecialchars($p['company_name']); ?></p>
                            </div>

                            <!-- Contact details -->
                            <div class="p-3 rounded-xl bg-slate-50 border border-slate-100 text-xs space-y-2">
                                <div class="flex items-center gap-2 text-slate-600">
                                    <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="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>
                                    <a href="mailto:<?php echo htmlspecialchars($p['email']); ?>" class="hover:text-indigo-600 truncate transition-colors">
                                        <?php echo htmlspecialchars($p['email']); ?>
                                    </a>
                                </div>
                                <div class="flex items-center gap-2 text-slate-600">
                                    <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="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>
                                    <a href="tel:<?php echo htmlspecialchars($p['mobile_number']); ?>" class="hover:text-indigo-600 font-mono transition-colors">
                                        <?php echo htmlspecialchars($p['mobile_number'] ?: 'No mobile set'); ?>
                                    </a>
                                </div>
                            </div>

                            <!-- Assigned Project Artifacts -->
                            <div class="space-y-2 pt-1">
                                <div class="flex items-center justify-between text-xs font-semibold text-slate-500">
                                    <span>Assigned Project Artifacts:</span>
                                    <span class="text-indigo-700 font-bold bg-indigo-50 px-2 py-0.5 rounded-md border border-indigo-100"><?php echo $art_count; ?></span>
                                </div>

                                <?php if ($art_count > 0): ?>
                                    <div class="space-y-1.5 max-h-36 overflow-y-auto pr-1">
                                        <?php foreach ($assigned_arts as $a): ?>
                                            <div class="p-2 rounded-lg bg-slate-50 border border-slate-200/80 text-[11px] space-y-1">
                                                <div class="flex items-center justify-between gap-1">
                                                    <div class="truncate pr-1">
                                                        <span class="font-mono font-bold text-indigo-700 mr-1">[<?php echo htmlspecialchars($a['project_code']); ?>]</span>
                                                        <span class="text-slate-900 font-semibold"><?php echo htmlspecialchars($a['title']); ?></span>
                                                    </div>
                                                    <span class="text-[9px] font-bold px-1.5 py-0.2 rounded bg-slate-200/70 text-slate-700 shrink-0">
                                                        <?php echo htmlspecialchars($a['status']); ?>
                                                    </span>
                                                </div>
                                                <div class="flex items-center justify-between pt-1 text-[10px] border-t border-slate-200/50">
                                                    <span class="text-slate-400 truncate"><?php echo htmlspecialchars($a['project_name']); ?></span>
                                                    <button type="button" onclick='openDispatchModal(<?php echo json_encode($p); ?>, <?php echo json_encode($a); ?>)' class="text-indigo-600 hover:text-indigo-800 font-bold flex items-center gap-0.5">
                                                        <span>🔗 Link</span>
                                                    </button>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="p-2.5 rounded-xl bg-amber-50 border border-amber-200 text-[11px] text-amber-800 space-y-0.5">
                                        <div class="font-bold flex items-center gap-1">
                                            <span>⚠️ No Artifacts Assigned</span>
                                        </div>
                                        <p class="text-[10px] text-amber-700 leading-relaxed">
                                            Links relate directly to a specific QC checklist. Assign this partner to an artifact in Project Details first.
                                        </p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Card Footer Controls -->
                        <div class="pt-3 border-t border-slate-100 flex items-center justify-between gap-2">
                            <button onclick='openEditModal(<?php echo json_encode($p); ?>)' class="px-3 py-1.5 rounded-lg border border-slate-200 hover:bg-slate-50 text-slate-700 text-xs font-semibold transition-colors inline-flex items-center gap-1">
                                <svg class="w-3.5 h-3.5 text-slate-400" 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>Edit</span>
                            </button>

                            <div class="flex items-center gap-1.5">
                                <?php if ($art_count > 0): ?>
                                    <!-- Artifact-Specific Link Dispatch -->
                                    <button onclick='openDispatchModal(<?php echo json_encode($p); ?>)' class="px-2.5 py-1.5 rounded-lg bg-indigo-50 hover:bg-indigo-100 text-indigo-700 text-xs font-semibold transition-colors inline-flex items-center gap-1" title="Generate and send artifact 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="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>Send Link (<?php echo $art_count; ?>)</span>
                                    </button>
                                <?php else: ?>
                                    <a href="dashboard.php" class="px-2.5 py-1.5 rounded-lg text-slate-400 hover:text-indigo-600 text-xs font-semibold" title="Go to projects to assign checklists">
                                        Assign in Projects &rarr;
                                    </a>
                                <?php endif; ?>

                                <form action="partners.php" method="POST" onsubmit="return confirm('Remove partner <?php echo htmlspecialchars(addslashes($p['person_name'])); ?>?');">
                                    <input type="hidden" name="action" value="delete_partner">
                                    <input type="hidden" name="partner_id" value="<?php echo htmlspecialchars($p['id']); ?>">
                                    <button type="submit" class="p-1.5 rounded-lg text-rose-500 hover:bg-rose-50 hover:text-rose-700 transition-colors" title="Delete partner">
                                        <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                    </button>
                                </form>
                            </div>
                        </div>

                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    </main>

    <!-- ==================== DISPATCH ARTIFACT LINK MODAL ==================== -->
    <div id="dispatch-link-modal" class="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 hidden overflow-y-auto">
        <div class="bg-white rounded-2xl max-w-lg w-full p-6 sm:p-8 shadow-2xl border border-slate-200 space-y-5">
            <div class="flex items-center justify-between border-b border-slate-100 pb-3">
                <div>
                    <h2 class="text-xl font-bold text-slate-900">Dispatch Artifact Site Link</h2>
                    <p class="text-xs text-slate-500 mt-0.5">Generate a secure token for this partner to complete an on-site checklist.</p>
                </div>
                <button onclick="closeDispatchModal()" class="text-slate-400 hover:text-slate-600 font-bold p-1">✕</button>
            </div>

            <form action="partners.php" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="dispatch_link">
                <input type="hidden" name="partner_id" id="dispatch-partner-id" value="">

                <!-- Partner Summary -->
                <div class="p-3.5 bg-slate-50 rounded-xl border border-slate-200 text-xs space-y-1.5">
                    <div class="flex items-center justify-between">
                        <span class="text-slate-400">Recipient Partner:</span>
                        <span class="font-bold text-slate-900" id="dispatch-partner-name">-</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-slate-400">Email Address:</span>
                        <span class="font-medium text-slate-700" id="dispatch-partner-email">-</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-slate-400">Mobile SMS:</span>
                        <span class="font-mono text-slate-700" id="dispatch-partner-mobile">-</span>
                    </div>
                </div>

                <!-- Select Target Artifact -->
                <div>
                    <label class="block text-xs font-bold text-slate-700 mb-1">Select Target Project Artifact *</label>
                    <select name="project_artifact_id" id="dispatch-artifact-select" required onchange="updateLinkPreview()" class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-xs font-medium focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                        <!-- Populated by JavaScript -->
                    </select>
                </div>

                <!-- Generated Link Preview & Copy -->
                <div class="space-y-1.5">
                    <div class="flex items-center justify-between text-xs font-bold text-slate-700">
                        <span>Access Link URL (Token valid 7 days)</span>
                        <span id="copy-status-text" class="text-emerald-600 text-[10px] hidden font-semibold">✓ Copied to clipboard</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <input type="text" id="dispatch-url-preview" readonly class="w-full px-3 py-2 bg-slate-100 border border-slate-200 rounded-xl text-xs font-mono text-slate-700 select-all outline-none" value="">
                        <button type="button" onclick="copyAccessLink()" class="px-3.5 py-2 rounded-xl bg-slate-200 hover:bg-slate-300 text-slate-700 text-xs font-bold transition-all shrink-0">
                            Copy
                        </button>
                    </div>
                </div>

                <!-- SMS/Email Dispatch Preview -->
                <div class="p-3 bg-slate-900 text-slate-200 rounded-xl text-xs space-y-1">
                    <div class="text-[10px] font-bold text-indigo-400 uppercase tracking-wider flex items-center gap-1">
                        <span>📱 SMS & Email Message Preview</span>
                    </div>
                    <p id="dispatch-sms-preview" class="text-[11px] text-slate-300 font-mono leading-relaxed">
                        -
                    </p>
                </div>

                <div class="flex items-center justify-end gap-3 pt-3 border-t border-slate-100">
                    <button type="button" onclick="closeDispatchModal()" class="px-4 py-2.5 rounded-xl border border-slate-200 text-slate-600 text-xs font-semibold hover:bg-slate-50">
                        Close
                    </button>
                    <button type="submit" class="px-6 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold shadow-sm flex items-center gap-1.5">
                        <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 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
                        <span>Dispatch Invite via SMS & Email</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ==================== CREATE PARTNER MODAL ==================== -->
    <div id="create-partner-modal" class="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 hidden overflow-y-auto">
        <div class="bg-white rounded-2xl max-w-lg w-full p-6 sm:p-8 shadow-2xl border border-slate-200 space-y-6">
            <div class="flex items-center justify-between border-b border-slate-100 pb-4">
                <div>
                    <h2 class="text-xl font-bold text-slate-900">Add Subcontractor Partner</h2>
                    <p class="text-xs text-slate-500 mt-0.5">Stored at company level and assignable to any project.</p>
                </div>
                <button onclick="closeCreateModal()" class="text-slate-400 hover:text-slate-600 font-bold p-1">✕</button>
            </div>

            <form action="partners.php" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="create_partner">

                <div>
                    <label class="block text-xs font-bold text-slate-700 mb-1">Contact Person Name *</label>
                    <input type="text" name="person_name" required placeholder="e.g. John Doe" class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                </div>

                <div>
                    <label class="block text-xs font-bold text-slate-700 mb-1">Subcontractor Company Name *</label>
                    <input type="text" name="company_name" required placeholder="e.g. Apex Electrical Solutions Ltd" class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                </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">Email Address *</label>
                        <input type="email" name="email" required placeholder="e.g. john@apexelectrical.com" class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 mb-1">Mobile Phone Number *</label>
                        <input type="tel" name="mobile_number" required placeholder="e.g. +44 7700 900123" class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                    </div>
                </div>

                <div class="p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs text-slate-500 flex items-start gap-2">
                    <svg class="w-4 h-4 text-indigo-600 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    <span>Partners are project-agnostic. Once created, they can be assigned to checklists across any project in your account.</span>
                </div>

                <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100">
                    <button type="button" onclick="closeCreateModal()" class="px-4 py-2.5 rounded-xl border border-slate-200 text-slate-600 text-xs font-semibold hover:bg-slate-50">
                        Cancel
                    </button>
                    <button type="submit" class="px-6 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold shadow-sm">
                        Save Partner
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ==================== EDIT PARTNER MODAL ==================== -->
    <div id="edit-partner-modal" class="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 hidden overflow-y-auto">
        <div class="bg-white rounded-2xl max-w-lg w-full p-6 sm:p-8 shadow-2xl border border-slate-200 space-y-6">
            <div class="flex items-center justify-between border-b border-slate-100 pb-4">
                <div>
                    <h2 class="text-xl font-bold text-slate-900">Edit Subcontractor Partner</h2>
                    <p class="text-xs text-slate-500 mt-0.5">Update partner contact and company details.</p>
                </div>
                <button onclick="closeEditModal()" class="text-slate-400 hover:text-slate-600 font-bold p-1">✕</button>
            </div>

            <form action="partners.php" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="edit_partner">
                <input type="hidden" name="partner_id" id="edit-partner-id" value="">

                <div>
                    <label class="block text-xs font-bold text-slate-700 mb-1">Contact Person Name *</label>
                    <input type="text" name="person_name" id="edit-person-name" required class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                </div>

                <div>
                    <label class="block text-xs font-bold text-slate-700 mb-1">Subcontractor Company Name *</label>
                    <input type="text" name="company_name" id="edit-company-name" required class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                </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">Email Address *</label>
                        <input type="email" name="email" id="edit-email" required class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 mb-1">Mobile Phone Number *</label>
                        <input type="tel" name="mobile_number" id="edit-mobile" required class="w-full px-3.5 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none">
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100">
                    <button type="button" onclick="closeEditModal()" class="px-4 py-2.5 rounded-xl border border-slate-200 text-slate-600 text-xs font-semibold hover:bg-slate-50">
                        Cancel
                    </button>
                    <button type="submit" class="px-6 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold shadow-sm">
                        Update Partner
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- JavaScript Handlers & Data Map -->
    <script>
        const partnerArtifactsData = <?php echo json_encode($partner_artifacts_map); ?>;

        function openCreateModal() {
            document.getElementById('create-partner-modal').classList.remove('hidden');
        }

        function closeCreateModal() {
            document.getElementById('create-partner-modal').classList.add('hidden');
        }

        function openEditModal(partner) {
            document.getElementById('edit-partner-id').value = partner.id;
            document.getElementById('edit-person-name').value = partner.person_name || '';
            document.getElementById('edit-company-name').value = partner.company_name || '';
            document.getElementById('edit-email').value = partner.email || '';
            document.getElementById('edit-mobile').value = partner.mobile_number || '';
            document.getElementById('edit-partner-modal').classList.remove('hidden');
        }

        function closeEditModal() {
            document.getElementById('edit-partner-modal').classList.add('hidden');
        }

        let currentActivePartner = null;

        function openDispatchModal(partner, defaultArtifact = null) {
            currentActivePartner = partner;
            document.getElementById('dispatch-partner-id').value = partner.id;
            document.getElementById('dispatch-partner-name').innerText = partner.person_name + ' (' + partner.company_name + ')';
            document.getElementById('dispatch-partner-email').innerText = partner.email || 'None';
            document.getElementById('dispatch-partner-mobile').innerText = partner.mobile_number || 'None';

            const arts = partnerArtifactsData[partner.id] || [];
            const selectEl = document.getElementById('dispatch-artifact-select');
            selectEl.innerHTML = '';

            if (arts.length === 0) {
                alert('No artifacts assigned to this partner yet. Please assign a checklist in Project Details first.');
                return;
            }

            arts.forEach(art => {
                const opt = document.createElement('option');
                opt.value = art.id;
                opt.text = '[' + art.project_code + '] ' + art.title + ' (' + art.project_name + ')';
                if (defaultArtifact && defaultArtifact.id === art.id) {
                    opt.selected = true;
                }
                selectEl.appendChild(opt);
            });

            updateLinkPreview();
            document.getElementById('dispatch-link-modal').classList.remove('hidden');
        }

        function closeDispatchModal() {
            document.getElementById('dispatch-link-modal').classList.add('hidden');
        }

        function updateLinkPreview() {
            const selectEl = document.getElementById('dispatch-artifact-select');
            const artId = selectEl.value;
            const arts = currentActivePartner ? (partnerArtifactsData[currentActivePartner.id] || []) : [];
            const selectedArt = arts.find(a => a.id === artId) || arts[0];

            const host = window.location.origin;
            const fakeToken = 'tk_' + (artId ? artId.replace(/[^a-zA-Z0-9]/g, '').substring(0, 16) : 'site789') + '_' + (currentActivePartner ? currentActivePartner.id.replace(/[^a-zA-Z0-9]/g, '').substring(0, 8) : 'demo');
            const fullUrl = host + '/partner_access.php?token=' + fakeToken;

            document.getElementById('dispatch-url-preview').value = fullUrl;
            
            if (currentActivePartner && selectedArt) {
                const smsMsg = 'Hi ' + currentActivePartner.person_name + ', please complete \'' + selectedArt.title + '\' on project ' + selectedArt.project_code + ' (' + selectedArt.project_name + '). Access the mobile checklist here: ' + fullUrl + ' (Valid 7 days)';
                document.getElementById('dispatch-sms-preview').innerText = smsMsg;
            }
        }

        function copyAccessLink() {
            const input = document.getElementById('dispatch-url-preview');
            input.select();
            navigator.clipboard.writeText(input.value);
            const statusEl = document.getElementById('copy-status-text');
            statusEl.classList.remove('hidden');
            setTimeout(() => {
                statusEl.classList.add('hidden');
            }, 2500);
        }

        function searchPartners() {
            const query = document.getElementById('partner-search-input').value.toLowerCase().trim();
            const cards = document.querySelectorAll('.partner-card');
            let visibleCount = 0;

            cards.forEach(card => {
                const searchData = card.getAttribute('data-search') || '';
                if (searchData.includes(query)) {
                    card.classList.remove('hidden');
                    visibleCount++;
                } else {
                    card.classList.add('hidden');
                }
            });

            const countEl = document.getElementById('partner-visible-count');
            if (countEl) {
                countEl.innerText = visibleCount;
            }
        }
    </script>

</body>
</html>