<?php
// init.php aur header.php ko shaamil karein
require_once 'init.php';
require_once 'header.php';

// Suraksha jaanch: Admin aur Manager dono dekh sakte hain
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: clients.php");
    exit();
}
$client_id = (int)$_GET['id'];
$items_per_page = 5;

// Permissions check
$isAdmin = userHasRole(['Admin']);
$canEdit = userHasRole(['Admin']); 

// --- AJAX PAGINATION ---
if (isset($_GET['fetch'])) {
    header('Content-Type: application/json');
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $offset = ($page - 1) * $items_per_page;
    $data_type = $_GET['fetch'];
    
    if ($data_type === 'tasks') {
        $task_sql = "SELECT t.*, u.name as assigned_user_name 
                     FROM tasks t JOIN users u ON t.assigned_user_id = u.id
                     WHERE t.client_id = ? AND t.status NOT IN ('Completed', 'Skipped')
                     ORDER BY t.assigned_date ASC LIMIT ? OFFSET ?";
        $task_stmt = $conn->prepare($task_sql);
        $task_stmt->bind_param("iii", $client_id, $items_per_page, $offset);
        $task_stmt->execute();
        echo json_encode($task_stmt->get_result()->fetch_all(MYSQLI_ASSOC));
        $task_stmt->close();
    } elseif ($data_type === 'reports') {
        $reports_sql = "SELECT cr.*, u.name as creator_name 
                        FROM client_reports cr JOIN users u ON cr.created_by_user_id = u.id 
                        WHERE cr.client_id = ? ORDER BY cr.report_date DESC LIMIT ? OFFSET ?";
        $reports_stmt = $conn->prepare($reports_sql);
        $reports_stmt->bind_param("iii", $client_id, $items_per_page, $offset);
        $reports_stmt->execute();
        echo json_encode($reports_stmt->get_result()->fetch_all(MYSQLI_ASSOC));
        $reports_stmt->close();
    }
    exit();
}

// --- POST ACTIONS ---
$message = '';
$message_type = '';
$show_decrypted_notes = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // 1. UPDATE CLIENT & NOTES FIX
    if (isset($_POST['update_client']) && $canEdit) {
        $name = $_POST['name'];
        $contact_person = $_POST['contact_person'];
        $contact_phone = $_POST['contact_phone'];
        $contact_email = $_POST['contact_email'];
        $activation_date = $_POST['activation_date'];
        $is_active = (int)$_POST['is_active'];
        $required_tasks_count = (int)$_POST['required_tasks_count'];
        $req_posts = (int)$_POST['required_posts_count'];
        $req_reels = (int)$_POST['required_reels_count'];
        $notes = $_POST['notes']; 

        $update_sql = "UPDATE clients SET name = ?, contact_person = ?, contact_phone = ?, contact_email = ?, activation_date = ?, is_active = ?, required_tasks_count = ?, required_posts_count = ?, required_reels_count = ?, notes = ? WHERE id = ?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("sssssiiiisi", $name, $contact_person, $contact_phone, $contact_email, $activation_date, $is_active, $required_tasks_count, $req_posts, $req_reels, $notes, $client_id);

        if ($stmt->execute()) {
            $message = "Client profile updated successfully!";
            $message_type = 'success';
        } else {
            $message = "Error: " . $stmt->error;
            $message_type = 'error';
        }
        $stmt->close();
    }

    // 2. PROFILE PHOTO UPDATE
    if (isset($_POST['upload_picture']) && $canEdit) {
        if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] == 0) {
            $target_dir = "uploads/clients/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            $file_ext = pathinfo($_FILES["profile_picture"]["name"], PATHINFO_EXTENSION);
            $file_name = "client_" . $client_id . "_" . time() . "." . $file_ext;
            $target_file = $target_dir . $file_name;

            if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
                $stmt = $conn->prepare("UPDATE clients SET profile_picture = ? WHERE id = ?");
                $stmt->bind_param("si", $target_file, $client_id);
                $stmt->execute();
                $message = "Photo updated successfully!";
                $message_type = 'success';
            }
        }
    }

    // Unlock Notes
    if (isset($_POST['unlock_notes'])) {
        $password = $_POST['password'];
        $user_id = $_SESSION['user_id'];
        $stmt = $conn->prepare("SELECT password_hash FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        if ($user && password_verify($password, $user['password_hash'])) {
            $show_decrypted_notes = true;
        } else {
            $message = "Incorrect password.";
            $message_type = 'error';
        }
    }

    // Delete Client
    if (isset($_POST['delete_client']) && $isAdmin) {
        $admin_password = $_POST['admin_password'];
        $stmt = $conn->prepare("SELECT password_hash FROM users WHERE id = ?");
        $stmt->bind_param("i", $_SESSION['user_id']);
        $stmt->execute();
        $admin_user = $stmt->get_result()->fetch_assoc();
        if ($admin_user && password_verify($admin_password, $admin_user['password_hash'])) {
            $conn->query("DELETE FROM clients WHERE id = $client_id");
            header("Location: clients.php?message=deleted");
            exit();
        }
    }
}

// --- DATA FETCHING ---
$stmt = $conn->prepare("SELECT * FROM clients WHERE id = ?");
$stmt->bind_param("i", $client_id);
$stmt->execute();
$client = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$client) { header("Location: clients.php"); exit(); }

// --- NEW BILLING CYCLE LOGIC ---
$act_day = date('d', strtotime($client['activation_date']));
$current_day = date('d');
$current_month = date('m');
$current_year = date('Y');

if ($current_day >= $act_day) {
    $default_start = "$current_year-$current_month-$act_day";
} else {
    $default_start = date('Y-m-d', strtotime("-1 month", strtotime("$current_year-$current_month-$act_day")));
}

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : $default_start;
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Performance Logic (Workflow Optimized)
$stats_sql = "SELECT 
    -- 1. Regular Execution (Posts & Reels)
    SUM(CASE WHEN work_type = 'Post' AND task_type = 'Regular' AND status = 'Completed' THEN 1 ELSE 0 END) as reg_posts_done,
    SUM(CASE WHEN work_type = 'Reel' AND task_type = 'Regular' AND status = 'Completed' THEN 1 ELSE 0 END) as reg_reels_done,
    SUM(CASE WHEN task_type = 'Regular' AND status = 'Completed' THEN 1 ELSE 0 END) as total_reg_done,
    
    -- 2. Insta Posted (Reviewer is Assignee, same person live kar raha hai, excluding reports)
    SUM(CASE WHEN assigned_user_id = smm_user_id AND work_type != 'Report' AND status = 'Completed' THEN 1 ELSE 0 END) as insta_posted,
    
    -- 3. Clean Additional (Na Regular, Na Posting task, Na Report)
    SUM(CASE WHEN task_type = 'Additional' AND assigned_user_id != smm_user_id AND work_type != 'Report' AND status = 'Completed' THEN 1 ELSE 0 END) as clean_add_done
    
    FROM tasks WHERE client_id = ? AND (completed_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59')";

$st_stmt = $conn->prepare($stats_sql);
$st_stmt->bind_param("i", $client_id);
$st_stmt->execute();
$st = $st_stmt->get_result()->fetch_assoc();

// Initial lists
$active_tasks_initial = $conn->query("SELECT t.*, u.name as assigned_user_name FROM tasks t JOIN users u ON t.assigned_user_id = u.id WHERE t.client_id = $client_id AND t.status NOT IN ('Completed', 'Skipped') ORDER BY t.assigned_date ASC LIMIT $items_per_page")->fetch_all(MYSQLI_ASSOC);
$reports_initial = $conn->query("SELECT cr.*, u.name as creator_name FROM client_reports cr JOIN users u ON cr.created_by_user_id = u.id WHERE cr.client_id = $client_id ORDER BY cr.report_date DESC LIMIT $items_per_page")->fetch_all(MYSQLI_ASSOC);
$reports_for_js = json_encode($conn->query("SELECT * FROM client_reports WHERE client_id = $client_id ORDER BY report_date DESC")->fetch_all(MYSQLI_ASSOC));
?>

<title>Client Profile: <?php echo htmlspecialchars($client['name']); ?></title>

<div class="flex-1" x-data="clientProfile()">
    <header class="bg-white shadow-sm p-4 flex justify-between items-center border-b">
        <h2 class="text-xl font-bold text-gray-800 uppercase tracking-tight">Client Profile</h2>
        <div class="flex items-center gap-4">
            <div class="text-sm font-bold text-blue-600 mr-2"><?php echo htmlspecialchars($client['name']); ?></div>
            <form method="GET" class="flex items-center gap-2 bg-gray-50 p-1 px-3 rounded-xl border border-gray-200">
                <input type="hidden" name="id" value="<?= $client_id ?>">
                <span class="text-[9px] font-bold text-gray-400 uppercase">Cycle:</span>
                <input type="date" name="start_date" value="<?= $start_date ?>" class="text-[10px] border-none bg-transparent font-bold p-1 focus:ring-0">
                <span class="text-gray-300">to</span>
                <input type="date" name="end_date" value="<?= $end_date ?>" class="text-[10px] border-none bg-transparent font-bold p-1 focus:ring-0">
                <button type="submit" class="bg-blue-600 text-white px-3 py-1 rounded-lg text-[9px] font-bold uppercase hover:bg-blue-700 transition">Apply</button>
            </form>
        </div>
    </header>

<main class="p-6 md:p-10">
    <?php if ($message): ?>
        <div class="mb-4 p-4 rounded-xl font-bold text-sm <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>

    <div class="bg-white p-6 rounded-3xl shadow-sm mb-8 flex flex-col md:flex-row items-start gap-6 border border-gray-100">
        <div class="flex-shrink-0 text-center">
            <img src="<?php echo !empty($client['profile_picture']) ? htmlspecialchars($client['profile_picture']) : 'https://via.placeholder.com/128/E0E7FF/4F46E5?text=No+Image'; ?>" class="h-32 w-32 rounded-3xl object-cover border-4 border-gray-100 shadow-sm mx-auto">
            <?php if($canEdit): ?>
                <button @click="isUploadModalOpen = true" class="mt-2 text-[10px] text-blue-600 hover:underline uppercase font-bold">Update Picture</button>
            <?php endif; ?>
        </div>
        <div class="flex-grow w-full">
            <div class="flex justify-between items-start">
                <div>
                    <h2 class="text-3xl font-bold text-gray-900 uppercase tracking-tighter"><?php echo htmlspecialchars($client['name']); ?></h2>
                    <p class="text-gray-500 font-bold uppercase text-[10px] tracking-widest"><?php echo htmlspecialchars($client['contact_person']); ?></p>
                </div>
                <div class="flex gap-2">
                    <span class="px-3 py-1 text-[10px] font-bold rounded-lg <?php echo $client['is_active'] ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'; ?> uppercase"><?php echo $client['is_active'] ? 'Active' : 'Inactive'; ?></span>
                    <?php if($canEdit): ?>
                        <button @click="isEditModalOpen = true" class="bg-indigo-600 text-white px-4 py-1 rounded-xl text-[10px] font-bold shadow-sm hover:bg-indigo-700">EDIT PROFILE</button>
                    <?php endif; ?>
                </div>
            </div>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6 pt-4 border-t border-gray-50">
                <div class="text-[9px] text-gray-400 font-bold uppercase">Phone: <span class="text-gray-900 block font-bold text-xs"><?php echo htmlspecialchars($client['contact_phone']); ?></span></div>
                <div class="text-[9px] text-gray-400 font-bold uppercase">Email: <span class="text-gray-900 block font-bold text-xs"><?php echo htmlspecialchars($client['contact_email'] ?? 'N/A'); ?></span></div>
                <div class="text-[9px] text-gray-400 font-bold uppercase">Activation: <span class="text-gray-900 block font-bold text-xs"><?php echo date("d M, Y", strtotime($client['activation_date'])); ?></span></div>
                <div class="text-[9px] text-gray-400 font-bold uppercase">Target: <span class="text-blue-600 block font-bold text-xs"><?= $client['required_posts_count'] ?>P / <?= $client['required_reels_count'] ?>R</span></div>
            </div>
        </div>
    </div>

    <div class="bg-white p-6 rounded-3xl shadow-sm mb-8 border border-gray-100">
        <h3 class="text-[10px] font-bold text-gray-400 mb-6 uppercase tracking-widest">Real-time Performance (Selected Cycle)</h3>
        <div class="grid grid-cols-2 md:grid-cols-5 gap-3 text-center">
            <div class="p-3 bg-blue-50 rounded-2xl border border-blue-100">
                <p class="text-xl font-bold text-blue-700"><?= (int)$st['reg_posts_done'] ?> / <?= $client['required_posts_count'] ?></p>
                <p class="text-[9px] font-bold text-gray-500 uppercase">Reg. Posts</p>
            </div>
            <div class="p-3 bg-purple-50 rounded-2xl border border-purple-100">
                <p class="text-xl font-bold text-purple-700"><?= (int)$st['reg_reels_done'] ?> / <?= $client['required_reels_count'] ?></p>
                <p class="text-[9px] font-bold text-gray-500 uppercase">Reg. Reels</p>
            </div>
            <div class="p-3 bg-green-50 rounded-2xl border border-green-100 shadow-sm">
                <p class="text-xl font-bold text-green-700">
                    <?= (int)$st['total_reg_done'] ?> / <?= (int)$client['required_posts_count'] + (int)$client['required_reels_count'] ?>
                </p>
                <p class="text-[9px] font-bold text-gray-700 uppercase">Total Target</p>
            </div>
            <div class="p-3 bg-pink-50 rounded-2xl border border-pink-100 shadow-sm">
                <p class="text-xl font-bold text-pink-700"><?= (int)$st['insta_posted'] ?></p>
                <p class="text-[9px] font-bold text-gray-500 uppercase">Insta Posted</p>
            </div>
            <div class="p-3 bg-gray-50 rounded-2xl border border-gray-200">
                <p class="text-xl font-bold text-gray-700"><?= (int)$st['clean_add_done'] ?></p>
                <p class="text-[9px] font-bold text-gray-500 uppercase">Additional</p>
            </div>
        </div>
    </div>

    <div class="border-b border-gray-200">
        <nav class="-mb-px flex space-x-8">
            <a href="#" @click.prevent="tab = 'active_tasks'" :class="tab === 'active_tasks' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500'" class="py-4 px-1 border-b-2 font-bold text-[10px] uppercase">Active Tasks</a>
            <a href="#" @click.prevent="tab = 'secure_notes'" :class="tab === 'secure_notes' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500'" class="py-4 px-1 border-b-2 font-bold text-[10px] uppercase">Secure Notes</a>
            <a href="#" @click.prevent="tab = 'reports'" :class="tab === 'reports' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500'" class="py-4 px-1 border-b-2 font-bold text-[10px] uppercase tracking-widest">10-Day Reports</a>
        </nav>
    </div>

    <div x-show="tab === 'active_tasks'" class="mt-6 bg-white rounded-3xl shadow-sm overflow-hidden border border-gray-50">
        <table class="min-w-full divide-y divide-gray-50">
            <thead class="bg-gray-50">
                <tr><th class="px-6 py-3 text-left text-[9px] font-bold text-gray-400 uppercase">Task</th><th class="px-6 py-3 text-left text-[9px] font-bold text-gray-400 uppercase">Assignee</th><th class="px-6 py-3 text-left text-[9px] font-bold text-gray-400 uppercase">Status</th><th class="px-6 py-3 text-left text-[9px] font-bold text-gray-400 uppercase">Action</th></tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-50">
                <template x-for="task in activeTasks" :key="task.id">
                    <tr class="hover:bg-gray-50 transition">
                        <td class="px-6 py-4 text-xs font-bold text-gray-900" x-text="task.title"></td>
                        <td class="px-6 py-4 text-xs font-bold text-gray-500" x-text="task.assigned_user_name"></td>
                        <td class="px-6 py-4"><span class="px-2 py-1 rounded-lg text-[9px] font-bold uppercase" :class="task.status == 'In Review' ? 'bg-yellow-100 text-yellow-700' : 'bg-blue-100 text-blue-700'" x-text="task.status"></span></td>
                        <td class="px-6 py-4"><button @click="viewTaskDetails(task)" class="text-blue-600 font-bold text-[10px] uppercase">VIEW</button></td>
                    </tr>
                </template>
                <tr x-show="!noMoreTasks" x-intersect:enter="loadMoreTasks()"><td colspan="4" class="p-1"></td></tr>
            </tbody>
        </table>
    </div>

    <div x-show="tab === 'secure_notes'" class="mt-6 bg-white p-8 rounded-3xl shadow-sm border border-gray-50 max-w-lg mx-auto text-center">
        <?php if ($show_decrypted_notes): ?>
            <h3 class="font-bold mb-4 uppercase text-[10px] text-gray-400 italic">Unlocked Content</h3>
            <div class="p-6 bg-gray-50 rounded-2xl border border-dashed text-left text-sm font-bold text-gray-700 leading-relaxed"><?php echo htmlspecialchars($client['notes'] ?? 'No notes.'); ?></div>
        <?php else: ?>
            <h3 class="font-bold text-center mb-6 uppercase text-[10px] tracking-widest text-gray-400">Locked Content</h3>
            <form method="POST"><input type="password" name="password" class="w-full border-gray-100 rounded-2xl p-4 mb-4 bg-gray-50 text-center font-bold" placeholder="Enter PIN" required><button type="submit" name="unlock_notes" class="w-full bg-gray-900 text-white py-3 rounded-2xl font-bold text-[10px] uppercase">UNLOCK</button></form>
        <?php endif; ?>
    </div>

    <div x-show="tab === 'reports'" class="mt-6 bg-white rounded-3xl shadow-sm overflow-hidden border border-gray-50">
        <table class="min-w-full divide-y divide-gray-50">
            <thead class="bg-gray-50 text-[9px] font-bold text-gray-400 uppercase">
                <tr><th class="px-6 py-3 text-left">Date</th><th class="px-6 py-3 text-left">Reviews</th><th class="px-6 py-3 text-left">Followers</th><th class="px-6 py-3 text-left">Action</th></tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-50">
                <template x-for="report in reports" :key="report.id">
                    <tr class="hover:bg-gray-50 transition">
                        <td class="px-6 py-4 text-xs font-bold" x-text="formatDate(report.report_date)"></td>
                        <td class="px-6 py-4 text-xs font-bold text-gray-700" x-text="report.google_reviews"></td>
                        <td class="px-6 py-4 text-xs font-bold text-gray-700" x-text="report.instagram_followers"></td>
                        <td class="px-6 py-4"><button class="text-blue-600 font-bold text-[9px] uppercase">Share</button></td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>

    <?php if ($isAdmin): ?>
    <div class="mt-16 bg-red-50 p-8 rounded-3xl border border-red-100 flex justify-between items-center">
        <div><h3 class="text-lg font-bold text-red-700 uppercase italic">Danger Zone</h3><p class="text-[9px] text-red-400 font-bold uppercase">Permanent deletion</p></div>
        <button @click="isDeleteModalOpen = true" class="bg-red-600 text-white font-bold py-3 px-8 rounded-2xl shadow-xl uppercase text-[10px]">DELETE CLIENT</button>
    </div>
    <?php endif; ?>
</main>

<div x-show="isUploadModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" style="display:none">
    <div class="bg-white p-8 rounded-3xl max-w-md w-full shadow-2xl">
        <h3 class="text-xl font-bold mb-6 border-b pb-2 uppercase">Update Picture</h3>
        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="profile_picture" required class="w-full border p-2 rounded mb-4">
            <div class="flex justify-end gap-2">
                <button type="button" @click="isUploadModalOpen = false" class="px-4 py-2 border rounded font-bold uppercase text-xs">Cancel</button>
                <button type="submit" name="upload_picture" class="bg-blue-600 text-white px-4 py-2 rounded font-bold uppercase text-xs">Upload</button>
            </div>
        </form>
    </div>
</div>

<?php if($canEdit): ?>
<div x-show="isEditModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" style="display:none">
    <div class="bg-white p-8 rounded-3xl max-w-2xl w-full max-h-[90vh] overflow-y-auto shadow-2xl">
        <h3 class="text-2xl font-bold mb-6 border-b pb-2 text-indigo-700 uppercase">Edit Profile</h3>
        <form method="POST">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div><label class="block text-[10px] font-bold text-gray-400 uppercase">Name</label><input type="text" name="name" value="<?= htmlspecialchars($client['name']) ?>" required class="w-full border rounded p-2 font-bold"></div>
                <div><label class="block text-[10px] font-bold text-gray-400 uppercase">Contact</label><input type="text" name="contact_person" value="<?= htmlspecialchars($client['contact_person']) ?>" required class="w-full border rounded p-2 font-bold"></div>
                <div><label class="block text-[10px] font-bold text-gray-400 uppercase">Phone</label><input type="text" name="contact_phone" value="<?= htmlspecialchars($client['contact_phone']) ?>" required class="w-full border rounded p-2 font-bold"></div>
                <div><label class="block text-[10px] font-bold text-gray-400 uppercase">Email</label><input type="email" name="contact_email" value="<?= htmlspecialchars($client['contact_email']) ?>" class="w-full border rounded p-2 font-bold"></div>
                <div class="p-2 bg-blue-50 border rounded"><label class="block text-[10px] font-bold text-blue-500 uppercase">Post Target</label><input type="number" name="required_posts_count" value="<?= (int)$client['required_posts_count'] ?>" class="w-full border rounded p-2 mt-1 font-bold"></div>
                <div class="p-2 bg-purple-50 border rounded"><label class="block text-[10px] font-bold text-purple-500 uppercase">Reel Target</label><input type="number" name="required_reels_count" value="<?= (int)$client['required_reels_count'] ?>" class="w-full border rounded p-2 mt-1 font-bold"></div>
                <div><label class="block text-[10px] font-bold text-gray-400 uppercase">Activation</label><input type="date" name="activation_date" value="<?= $client['activation_date'] ?>" class="w-full border rounded p-2 font-bold"></div>
                <div><label class="block text-[10px] font-bold text-gray-400 uppercase">Status</label><select name="is_active" class="w-full border rounded p-2 font-bold"><option value="1" <?= $client['is_active']?'selected':'' ?>>Active</option><option value="0" <?= !$client['is_active']?'selected':'' ?>>Inactive</option></select></div>
                <input type="hidden" name="required_tasks_count" value="<?= (int)$client['required_tasks_count'] ?>">
            </div>
            <div class="mt-4"><label class="block text-[10px] font-bold text-indigo-400 uppercase">Notes</label><textarea name="notes" rows="6" class="w-full border rounded p-2 font-bold text-sm shadow-inner"><?= htmlspecialchars($client['notes']) ?></textarea></div>
            <div class="flex justify-end gap-2 mt-8"><button type="button" @click="isEditModalOpen = false" class="px-6 py-2 border rounded font-bold uppercase text-xs text-gray-400">Cancel</button><button type="submit" name="update_client" class="bg-indigo-600 text-white px-8 py-2 rounded font-bold shadow-lg text-xs uppercase tracking-wider">Save changes</button></div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if($isAdmin): ?>
<div x-show="isDeleteModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" style="display:none">
    <div class="bg-white p-8 rounded-3xl max-w-md w-full shadow-2xl text-center">
        <h3 class="text-xl font-bold text-red-600 mb-4 uppercase">Authorize Delete</h3>
        <form method="POST">
            <input type="password" name="admin_password" required class="w-full border rounded p-3 mb-6 bg-gray-50 text-center" placeholder="Admin PIN">
            <div class="flex justify-center gap-3"><button type="button" @click="isDeleteModalOpen = false" class="px-4 py-2 text-gray-400 font-bold uppercase text-xs">Back</button><button type="submit" name="delete_client" class="bg-red-600 text-white px-6 py-2 rounded font-bold text-xs uppercase shadow-lg">Confirm Delete</button></div>
        </form>
    </div>
</div>
<?php endif; ?>

</div>

<script>
function clientProfile() {
    return {
        tab: 'active_tasks', isEditModalOpen: false, isDeleteModalOpen: false, isUploadModalOpen: false, isShareModalOpen: false,
        activeTasks: <?= json_encode($active_tasks_initial) ?>,
        reports: <?= json_encode($reports_initial) ?>,
        allReports: <?= $reports_for_js ?>,
        tasksPage: 1,
        loadMoreTasks() {
            fetch(`client-profile.php?id=<?= $client_id ?>&fetch=tasks&page=${this.tasksPage+1}`)
            .then(res => res.json()).then(data => { 
                if(data.length > 0) {
                    this.activeTasks = [...this.activeTasks, ...data];
                    this.tasksPage++;
                }
            });
        },
        formatDate(dateString) { return new Date(dateString).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }); },
        viewTaskDetails(task) { alert("TASK: " + task.title + "\n\nDESC: " + (task.description || "N/A")); }
    }
}
</script>

<?php require_once 'footer.php'; ?>