<?php
/**
 * Projects & Artifacts Team Dashboard
 * Location: public_html/team/dashboard.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 = '';

// Query Company Name & Primary Owner Name from Database
$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) {
    // Fallback to session values if query fails
}

// Handle Form Submissions (Create Project & Team Management)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'create_project') {
        $project_name = trim($_POST['project_name'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $client_name = trim($_POST['client_name'] ?? '');
        $client_email = trim($_POST['client_email'] ?? '');
        $client_mobile = trim($_POST['client_mobile'] ?? '');
        $access_level = $_POST['access_level'] ?? 'INTERNAL_ALL';

        if (empty($project_name) || empty($client_name)) {
            $action_error = "Project name and client name are required.";
        } else {
            try {
                // Dynamically generate project code: PRJ-XXX-YYSSS (e.g. PRJ-WAT-26001)
                $clean_name = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $project_name));
                $name_code = str_pad(substr($clean_name, 0, 3), 3, 'X');
                if (strlen($name_code) < 3) {
                    $name_code = 'PRJ';
                }
                
                $year_2digit = date('y');
                $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM projects WHERE account_id = ?");
                $stmt_count->execute([$account_id]);
                $seq_num = (int)$stmt_count->fetchColumn() + 1;
                $seq_padded = sprintf("%03d", $seq_num);
                $project_code = "PRJ-{$name_code}-{$year_2digit}{$seq_padded}";

                $prj_id = 'prj_' . bin2hex(random_bytes(6));
                $stmt_add_prj = $pdo->prepare("INSERT INTO projects (id, account_id, project_code, project_name, address, client_name, client_email, client_mobile, access_level, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE')");
                $stmt_add_prj->execute([$prj_id, $account_id, $project_code, $project_name, $address, $client_name, $client_email, $client_mobile, $access_level]);
                $action_success = "New building project <strong>" . htmlspecialchars($project_name) . "</strong> (Code: <code>" . htmlspecialchars($project_code) . "</code>) created successfully!";
            } catch (Exception $e) {
                $action_error = "Error creating project: " . $e->getMessage();
            }
        }
    } elseif ($action === 'invite_member') {
        if ($user_role !== 'PRIMARY_ADMIN') {
            $action_error = "Unauthorized action. Only Primary Administrators can manage team members.";
        } else {
            $first_name = trim($_POST['first_name'] ?? '');
            $last_name = trim($_POST['last_name'] ?? '');
            $invite_email = filter_var(trim($_POST['invite_email'] ?? ''), FILTER_VALIDATE_EMAIL);
            $invite_role = $_POST['invite_role'] ?? 'TEAM_MEMBER';

            if (empty($first_name) || empty($last_name)) {
                $action_error = "First name and last name are required.";
            } elseif (!$invite_email) {
                $action_error = "Please enter a valid email address.";
            } else {
                $stmt_check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
                $stmt_check->execute([$invite_email]);
                if ($stmt_check->fetch()) {
                    $action_error = "A user with this email address already exists in the system.";
                } else {
                    try {
                        $token = generate_token(16);
                        $expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));
                        $inv_id = 'inv_' . bin2hex(random_bytes(6));

                        $stmt_inv = $pdo->prepare("INSERT INTO team_invitations (id, account_id, invited_by_user_id, email, first_name, last_name, role, invite_token, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt_inv->execute([$inv_id, $account_id, $user_id, $invite_email, $first_name, $last_name, $invite_role, $token, $expires_at]);

                        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
                        $host = $_SERVER['HTTP_HOST'];
                        $invite_link = "{$protocol}://{$host}/team_register.php?token={$token}";

                        send_team_invitation_email($invite_email, $first_name, $company_name, $invite_link);

                        $action_success = "Invitation sent to <strong>" . htmlspecialchars($first_name . ' ' . $last_name) . "</strong> (" . htmlspecialchars($invite_email) . ")!";
                    } catch (Exception $e) {
                        $action_error = "Error sending invitation: " . $e->getMessage();
                    }
                }
            }
        }
    } elseif ($action === 'update_member') {
        if ($user_role !== 'PRIMARY_ADMIN') {
            $action_error = "Unauthorized action. Only Primary Administrators can update team members.";
        } else {
            $member_id = trim($_POST['member_id'] ?? '');
            $first_name = trim($_POST['first_name'] ?? '');
            $last_name = trim($_POST['last_name'] ?? '');
            $role = $_POST['role'] ?? 'TEAM_MEMBER';
            $status = $_POST['status'] ?? 'ACTIVE';

            if (empty($member_id) || empty($first_name) || empty($last_name)) {
                $action_error = "First name and last name are required.";
            } else {
                try {
                    $stmt_upd = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, role = ?, status = ? WHERE id = ? AND account_id = ?");
                    $stmt_upd->execute([$first_name, $last_name, $role, $status, $member_id, $account_id]);

                    if ($member_id === $user_id) {
                        $_SESSION['first_name'] = $first_name;
                        $_SESSION['last_name'] = $last_name;
                        $_SESSION['role'] = $role;
                        $user_role = $role;
                    }

                    $action_success = "Team member details updated successfully!";
                } catch (Exception $e) {
                    $action_error = "Error updating member: " . $e->getMessage();
                }
            }
        }
    } elseif ($action === 'delete_member') {
        if ($user_role !== 'PRIMARY_ADMIN') {
            $action_error = "Unauthorized action. Only Primary Administrators can delete team members.";
        } else {
            $member_id = trim($_POST['member_id'] ?? '');

            if ($member_id === $user_id) {
                $action_error = "You cannot delete your own account from this dashboard.";
            } else {
                try {
                    $stmt_del = $pdo->prepare("DELETE FROM users WHERE id = ? AND account_id = ?");
                    $stmt_del->execute([$member_id, $account_id]);

                    if ($stmt_del->rowCount() > 0) {
                        $action_success = "Team member removed from account.";
                    } else {
                        $action_error = "Team member not found or already deleted.";
                    }
                } catch (Exception $e) {
                    $action_error = "Error removing team member: " . $e->getMessage();
                }
            }
        }
    } elseif ($action === 'revoke_invite') {
        if ($user_role !== 'PRIMARY_ADMIN') {
            $action_error = "Unauthorized action.";
        } else {
            $invite_id = trim($_POST['invite_id'] ?? '');
            try {
                $stmt_rev = $pdo->prepare("DELETE FROM team_invitations WHERE id = ? AND account_id = ?");
                $stmt_rev->execute([$invite_id, $account_id]);
                $action_success = "Pending invitation revoked.";
            } catch (Exception $e) {
                $action_error = "Error revoking invitation: " . $e->getMessage();
            }
        }
    }
}

// Fetch Projects from Database
$stmt_proj = $pdo->prepare("SELECT * FROM projects WHERE account_id = ? ORDER BY created_at DESC");
$stmt_proj->execute([$account_id]);
$projects = $stmt_proj->fetchAll();

// Fetch Artifact Counts per Project
$stmt_arts = $pdo->prepare("
    SELECT pa.project_id, 
           COUNT(*) as total_arts, 
           SUM(CASE WHEN pa.status = 'COMPLETED' THEN 1 ELSE 0 END) as completed_arts 
    FROM project_artifacts pa 
    JOIN projects p ON pa.project_id = p.id 
    WHERE p.account_id = ? 
    GROUP BY pa.project_id
");
$stmt_arts->execute([$account_id]);
$art_counts_raw = $stmt_arts->fetchAll();
$art_counts = [];
foreach ($art_counts_raw as $ac) {
    $art_counts[$ac['project_id']] = [
        'total' => (int)$ac['total_arts'],
        'completed' => (int)$ac['completed_arts']
    ];
}

// Fetch Account Team Members
$stmt_team = $pdo->prepare("SELECT * FROM users WHERE account_id = ? ORDER BY role DESC, created_at ASC");
$stmt_team->execute([$account_id]);
$team_members = $stmt_team->fetchAll();

// Fetch Pending Invitations
$stmt_invs = $pdo->prepare("SELECT * FROM team_invitations WHERE account_id = ? AND status = 'PENDING' ORDER BY created_at DESC");
$stmt_invs->execute([$account_id]);
$pending_invites = $stmt_invs->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Projects & Artifacts Dashboard - <?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 min-h-screen text-slate-800">

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

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

        <?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; ?>

        <!-- ==================== SECTION 1: BUILDING PROJECTS ==================== -->
        <div class="space-y-6">
            <!-- Building Projects Header Card -->
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
                <div class="space-y-1">
                    <h2 class="text-xl font-bold text-slate-900">Building Projects</h2>
                    <p class="text-slate-500 text-xs">
                        Manage active site projects, attached QC checklists, compliance certificates, and client details.
                    </p>
                </div>
                <div class="flex items-center gap-2 shrink-0 flex-wrap">
                    <a href="partners.php" class="px-3.5 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 font-bold text-xs rounded-xl shadow-2xs transition-colors flex items-center gap-1.5">
                        <svg class="w-4 h-4 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
                        <span>Subcontractors & Partners</span>
                    </a>
                    <button onclick="document.getElementById('create-project-modal').classList.remove('hidden')" class="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs rounded-xl shadow-xs transition-colors flex items-center gap-1.5 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="M12 4v16m8-8H4"></path></svg>
                        + New Project
                    </button>
                </div>
            </div>

            <!-- Search and Filter Bar -->
            <div class="flex flex-col sm:flex-row items-center justify-between gap-4">
                <div class="relative w-full sm:w-96">
                    <input type="text" id="project-search-input" onkeyup="filterProjects()" placeholder="Search by code, project name, or client..." class="w-full pl-9 pr-4 py-2 bg-white border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all placeholder:text-slate-400">
                    <svg class="w-4 h-4 text-slate-400 absolute left-3 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>
                </div>

                <div class="flex items-center gap-2 w-full sm:w-auto">
                    <button onclick="setProjectStatusFilter('ALL', this)" class="filter-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-900 text-white">
                        All Projects (<?php echo count($projects); ?>)
                    </button>
                    <button onclick="setProjectStatusFilter('ACTIVE', this)" class="filter-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-white border border-slate-200 text-slate-600 hover:bg-slate-50">
                        Active (<?php echo count(array_filter($projects, fn($p) => ($p['status'] ?? 'ACTIVE') === 'ACTIVE')); ?>)
                    </button>
                    <button onclick="setProjectStatusFilter('CLOSED', this)" class="filter-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-white border border-slate-200 text-slate-600 hover:bg-slate-50">
                        Closed (<?php echo count(array_filter($projects, fn($p) => ($p['status'] ?? '') === 'CLOSED')); ?>)
                    </button>
                </div>
            </div>

            <!-- Projects Grid -->
            <?php if (empty($projects)): ?>
                <div class="text-center py-12 bg-white rounded-2xl border border-slate-200 p-8 space-y-3">
                    <div class="w-12 h-12 rounded-full bg-indigo-50 text-indigo-500 flex items-center justify-center mx-auto">
                        <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="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
                    </div>
                    <h3 class="text-base font-bold text-slate-900">No building projects yet</h3>
                    <p class="text-xs text-slate-500">Get started by creating your first site project to track QC compliance artifacts.</p>
                </div>
            <?php else: ?>
                <div id="projects-grid" class="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
                    <?php foreach ($projects as $prj): 
                        $pid = $prj['id'];
                        $total = $art_counts[$pid]['total'] ?? 0;
                        $completed = $art_counts[$pid]['completed'] ?? 0;
                        $pstatus = $prj['status'] ?? 'ACTIVE';
                    ?>
                        <div class="project-card bg-white border border-slate-200 rounded-2xl p-5 shadow-xs hover:border-indigo-300 hover:shadow-md transition-all flex flex-col justify-between space-y-4" data-status="<?php echo htmlspecialchars($pstatus); ?>" data-search="<?php echo htmlspecialchars(strtolower($prj['project_code'] . ' ' . $prj['project_name'] . ' ' . $prj['client_name'] . ' ' . $prj['address'])); ?>">
                            <div class="space-y-3">
                                <div class="flex items-start justify-between gap-2">
                                    <span class="px-2.5 py-1 rounded-md bg-slate-100 font-mono text-xs font-bold text-slate-700 border border-slate-200">
                                        <?php echo htmlspecialchars($prj['project_code']); ?>
                                    </span>
                                    <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold <?php echo $pstatus === 'CLOSED' ? 'bg-slate-100 text-slate-600 border border-slate-200' : 'bg-emerald-50 text-emerald-700 border border-emerald-200'; ?>">
                                        ● <?php echo $pstatus === 'CLOSED' ? 'Closed' : 'Active'; ?>
                                    </span>
                                </div>

                                <h3 class="text-base font-bold text-slate-900 leading-snug">
                                    <?php echo htmlspecialchars($prj['project_name']); ?>
                                </h3>

                                <p class="text-xs text-slate-500 flex items-start gap-1.5">
                                    <svg class="w-3.5 h-3.5 text-slate-400 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="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($prj['address']); ?></span>
                                </p>
                            </div>

                            <div class="p-3 rounded-xl bg-slate-50 border border-slate-100 text-xs space-y-1.5">
                                <div class="font-semibold text-slate-700 flex items-center justify-between">
                                    <span>👤 <?php echo htmlspecialchars($prj['client_name']); ?></span>
                                    <span class="text-[10px] text-slate-400 uppercase font-medium">Client</span>
                                </div>
                                <div class="text-slate-500 flex items-center justify-between text-[11px]">
                                    <span><?php echo htmlspecialchars($prj['client_email']); ?></span>
                                    <span><?php echo htmlspecialchars($prj['client_mobile']); ?></span>
                                </div>
                            </div>

                            <div class="pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
                                <div class="flex items-center gap-1.5 text-slate-600 font-semibold">
                                    <span class="text-indigo-600">📋 <?php echo $completed; ?> / <?php echo $total; ?></span>
                                    <span class="text-slate-400 font-normal">QC Artifacts</span>
                                </div>
                                <a href="project_details.php?id=<?php echo urlencode($prj['id']); ?>" class="text-indigo-600 hover:text-indigo-800 font-bold flex items-center gap-1">
                                    <span>View Project</span>
                                    →
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- ==================== SECTION 2: ADD TEAM MEMBER ==================== -->
        <div class="space-y-6 pt-6 border-t border-slate-200">
            <!-- Add Team Member Header Card (Styled Identically to Building Projects Header) -->
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 bg-white p-5 rounded-2xl border border-slate-200 shadow-xs">
                <div class="space-y-1">
                    <h2 class="text-xl font-bold text-slate-900">Add Team Member</h2>
                    <p class="text-slate-500 text-xs">
                        Manage your account team roster, invite co-administrators or project managers, and control member access.
                    </p>
                </div>
                <?php if ($user_role === 'PRIMARY_ADMIN'): ?>
                    <button onclick="document.getElementById('invite-modal').classList.remove('hidden')" class="px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs rounded-xl shadow-xs transition-colors flex items-center gap-1.5 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>
                        + Add Team Member
                    </button>
                <?php endif; ?>
            </div>

            <!-- Active Team Members Roster Grid -->
            <div class="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php foreach ($team_members as $m): ?>
                    <div class="p-5 rounded-2xl bg-white border border-slate-200 shadow-xs flex flex-col justify-between space-y-4">
                        <div class="space-y-2">
                            <div class="flex items-start justify-between gap-2">
                                <div>
                                    <h4 class="font-bold text-sm text-slate-900">
                                        <?php echo htmlspecialchars($m['first_name'] . ' ' . $m['last_name']); ?>
                                        <?php if ($m['id'] === $user_id): ?>
                                            <span class="text-[10px] text-indigo-600 font-medium ml-1">(You)</span>
                                        <?php endif; ?>
                                    </h4>
                                    <p class="text-xs text-slate-500 font-mono mt-0.5"><?php echo htmlspecialchars($m['email']); ?></p>
                                </div>
                                <span class="shrink-0 text-[10px] font-bold px-2 py-0.5 rounded-full <?php echo $m['role'] === 'PRIMARY_ADMIN' ? 'bg-indigo-100 text-indigo-800' : 'bg-slate-100 text-slate-700'; ?>">
                                    <?php echo $m['role'] === 'PRIMARY_ADMIN' ? 'Admin' : 'Member'; ?>
                                </span>
                            </div>

                            <div class="flex items-center gap-2 pt-1">
                                <span class="text-[10px] px-2 py-0.5 rounded font-semibold <?php echo ($m['status'] ?? 'ACTIVE') === 'ACTIVE' ? 'bg-emerald-100 text-emerald-800' : 'bg-amber-100 text-amber-800'; ?>">
                                    ● <?php echo htmlspecialchars($m['status'] ?? 'ACTIVE'); ?>
                                </span>
                            </div>
                        </div>

                        <?php if ($user_role === 'PRIMARY_ADMIN'): ?>
                            <div class="pt-3 border-t border-slate-100 flex items-center justify-end gap-2">
                                <button type="button"
                                    onclick="openEditModal('<?php echo htmlspecialchars($m['id'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($m['first_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($m['last_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($m['email'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($m['role'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($m['status'] ?? 'ACTIVE', ENT_QUOTES); ?>')"
                                    class="px-3 py-1.5 text-xs font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg transition-colors flex items-center gap-1">
                                    Edit
                                </button>

                                <?php if ($m['id'] !== $user_id): ?>
                                    <button type="button"
                                        onclick="openDeleteModal('<?php echo htmlspecialchars($m['id'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($m['first_name'] . ' ' . $m['last_name'], ENT_QUOTES); ?>')"
                                        class="px-3 py-1.5 text-xs font-semibold bg-rose-50 hover:bg-rose-100 text-rose-600 rounded-lg transition-colors flex items-center gap-1">
                                        Delete
                                    </button>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Pending Invitations Section -->
            <?php if (!empty($pending_invites)): ?>
                <div class="space-y-3 pt-2">
                    <h3 class="text-sm font-bold text-slate-800">Pending Invitations (<?php echo count($pending_invites); ?>)</h3>
                    <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden shadow-xs">
                        <div class="divide-y divide-slate-100">
                            <?php foreach ($pending_invites as $inv): ?>
                                <div class="p-4 flex items-center justify-between gap-4">
                                    <div>
                                        <div class="text-sm font-semibold text-slate-900"><?php echo htmlspecialchars($inv['email']); ?></div>
                                        <div class="text-xs text-slate-500 mt-0.5">
                                            Role: <span class="font-medium text-slate-700"><?php echo htmlspecialchars($inv['role']); ?></span> · 
                                            Expires: <?php echo date('M j, Y', strtotime($inv['expires_at'])); ?>
                                        </div>
                                    </div>
                                    <?php if ($user_role === 'PRIMARY_ADMIN'): ?>
                                        <form action="dashboard.php" method="POST" onsubmit="return confirm('Revoke this invitation?');">
                                            <input type="hidden" name="action" value="revoke_invite">
                                            <input type="hidden" name="invite_id" value="<?php echo htmlspecialchars($inv['id']); ?>">
                                            <button type="submit" class="text-xs px-3 py-1.5 rounded-lg border border-slate-200 hover:bg-slate-50 text-slate-600 font-semibold">
                                                Revoke
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

    </main>

    <!-- CREATE PROJECT MODAL -->
    <div id="create-project-modal" class="hidden fixed inset-0 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-2xl max-w-lg w-full p-6 shadow-2xl space-y-4">
            <div class="flex items-center justify-between border-b pb-3">
                <h3 class="font-bold text-slate-900 text-lg">Create New Building Project</h3>
                <button onclick="document.getElementById('create-project-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600 font-bold">✕</button>
            </div>
            <form action="dashboard.php" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="create_project">
                
                <div class="grid grid-cols-3 gap-3">
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Project Name *</label>
                        <input type="text" name="project_name" required placeholder="e.g. Waterfront Commercial Tower" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Access Level</label>
                        <select name="access_level" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                            <option value="INTERNAL_ALL">All Team Members</option>
                            <option value="MANAGERS_ONLY">Project Managers Only</option>
                            <option value="RESTRICTED">Restricted Confidential</option>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1">Site Street Address *</label>
                    <input type="text" name="address" required placeholder="e.g. 104 Ocean View Parade, Gold Coast QLD" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>

                <div class="p-3 bg-slate-50 border rounded-xl space-y-3">
                    <span class="text-xs font-bold text-slate-800 uppercase tracking-wider block">Client Contact Details</span>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Client Name *</label>
                        <input type="text" name="client_name" required placeholder="e.g. David Vance" class="w-full px-3 py-1.5 bg-white border rounded-lg text-sm">
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-xs font-semibold text-slate-600 mb-1">Client Email</label>
                            <input type="email" name="client_email" placeholder="client@company.com" class="w-full px-3 py-1.5 bg-white border rounded-lg text-sm">
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-slate-600 mb-1">Client Mobile</label>
                            <input type="tel" name="client_mobile" placeholder="+1 555-0192" class="w-full px-3 py-1.5 bg-white border rounded-lg text-sm">
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-2 pt-2">
                    <button type="button" onclick="document.getElementById('create-project-modal').classList.add('hidden')" class="px-4 py-2 border rounded-xl text-xs font-semibold 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 transition-colors">Create Project</button>
                </div>
            </form>
        </div>
    </div>

    <!-- INVITE TEAM MEMBER MODAL -->
    <div id="invite-modal" class="hidden fixed inset-0 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4">
            <div class="flex items-center justify-between border-b pb-3">
                <h3 class="font-bold text-slate-900 text-lg">Add Team Member</h3>
                <button onclick="document.getElementById('invite-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600 font-bold">✕</button>
            </div>
            <form action="dashboard.php" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="invite_member">
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">First Name *</label>
                        <input type="text" name="first_name" required placeholder="e.g. Sarah" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Last Name *</label>
                        <input type="text" name="last_name" required placeholder="e.g. Jenkins" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                    </div>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1">Colleague Email Address *</label>
                    <input type="email" name="invite_email" required class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none" placeholder="colleague@company.com">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1">Assigned Role</label>
                    <select name="invite_role" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                        <option value="TEAM_MEMBER">Team Member (Project Manager / Inspector)</option>
                        <option value="PRIMARY_ADMIN">Co-Administrator</option>
                    </select>
                </div>
                <div class="flex items-center justify-end gap-2 pt-2">
                    <button type="button" onclick="document.getElementById('invite-modal').classList.add('hidden')" class="px-4 py-2 border rounded-xl text-xs font-semibold 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 transition-colors">Send Invitation</button>
                </div>
            </form>
        </div>
    </div>

    <!-- EDIT MEMBER MODAL -->
    <div id="edit-modal" class="hidden fixed inset-0 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4">
            <div class="flex items-center justify-between border-b pb-3">
                <h3 class="font-bold text-slate-900 text-lg">Update Team Member</h3>
                <button onclick="document.getElementById('edit-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600 font-bold">✕</button>
            </div>
            <form action="dashboard.php" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="update_member">
                <input type="hidden" name="member_id" id="edit_member_id">
                
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">First Name</label>
                        <input type="text" name="first_name" id="edit_first_name" required class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Last Name</label>
                        <input type="text" name="last_name" id="edit_last_name" required class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                    </div>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1">Email Address</label>
                    <input type="email" id="edit_email" disabled class="w-full px-3 py-2 border rounded-xl text-sm bg-slate-100 text-slate-500">
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Role</label>
                        <select name="role" id="edit_role" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                            <option value="TEAM_MEMBER">Team Member</option>
                            <option value="PRIMARY_ADMIN">Primary Admin</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Status</label>
                        <select name="status" id="edit_status" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none">
                            <option value="ACTIVE">Active</option>
                            <option value="INACTIVE">Inactive</option>
                        </select>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-2 pt-2">
                    <button type="button" onclick="document.getElementById('edit-modal').classList.add('hidden')" class="px-4 py-2 border rounded-xl text-xs font-semibold 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 transition-colors">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <!-- DELETE MEMBER MODAL -->
    <div id="delete-modal" class="hidden fixed inset-0 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4">
            <div class="flex items-center justify-between border-b pb-3">
                <h3 class="font-bold text-slate-900 text-lg">Remove Team Member</h3>
                <button onclick="document.getElementById('delete-modal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600 font-bold">✕</button>
            </div>
            <form action="dashboard.php" method="POST" class="space-y-4">
                <input type="hidden" name="action" value="delete_member">
                <input type="hidden" name="member_id" id="delete_member_id">
                
                <p class="text-xs text-slate-600 leading-relaxed">
                    Are you sure you want to remove <strong id="delete_member_name" class="text-slate-900"></strong> from your account? This action cannot be undone and will revoke their access immediately.
                </p>

                <div class="flex items-center justify-end gap-2 pt-2">
                    <button type="button" onclick="document.getElementById('delete-modal').classList.add('hidden')" class="px-4 py-2 border rounded-xl text-xs font-semibold hover:bg-slate-50">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl shadow-xs transition-colors">Yes, Remove Member</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentStatusFilter = 'ALL';

        function filterProjects() {
            const query = document.getElementById('project-search-input').value.toLowerCase().trim();
            const cards = document.querySelectorAll('.project-card');

            cards.forEach(card => {
                const searchData = card.getAttribute('data-search') || '';
                const cardStatus = card.getAttribute('data-status') || 'ACTIVE';

                const matchesSearch = searchData.includes(query);
                const matchesStatus = currentStatusFilter === 'ALL' || cardStatus === currentStatusFilter;

                if (matchesSearch && matchesStatus) {
                    card.style.display = 'flex';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        function setProjectStatusFilter(status, btn) {
            currentStatusFilter = status;
            document.querySelectorAll('.filter-btn').forEach(b => {
                b.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-white border border-slate-200 text-slate-600 hover:bg-slate-50';
            });
            btn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-900 text-white';
            filterProjects();
        }

        function openEditModal(id, firstName, lastName, email, role, status) {
            document.getElementById('edit_member_id').value = id;
            document.getElementById('edit_first_name').value = firstName;
            document.getElementById('edit_last_name').value = lastName;
            document.getElementById('edit_email').value = email;
            document.getElementById('edit_role').value = role;
            document.getElementById('edit_status').value = status;
            document.getElementById('edit-modal').classList.remove('hidden');
        }

        function openDeleteModal(id, fullName) {
            document.getElementById('delete_member_id').value = id;
            document.getElementById('delete_member_name').textContent = fullName;
            document.getElementById('delete-modal').classList.remove('hidden');
        }
    </script>

</body>
</html>