<?php
/**
 * Clients Dashboard
 * Personal dashboard for clients with stats and quick access
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

// Get current user (client)
$client = $db->fetch(
    "SELECT id, name, email, phone FROM users 
     WHERE id = ? AND role = 'client'",
    [$_SESSION['user_id'] ?? 0]
);

if (!$client) {
    header('Location: ?page=dashboard');
    exit();
}

// Get statistics
$stats = [];

// Guards assigned to user's posts
$stats['guards'] = $db->fetch(
    "SELECT COUNT(DISTINCT gpa.guard_id) as count 
     FROM guard_post_assignments gpa
     JOIN posts p ON gpa.post_id = p.id
     WHERE p.owner_id = ?",
    [$_SESSION['user_id']]
);

// Posts
$stats['posts'] = $db->fetch(
    "SELECT COUNT(*) as count FROM posts 
     WHERE owner_id = ? AND status = 'Active'",
    [$_SESSION['user_id']]
);

// Controls recorded
$stats['controls'] = $db->fetch(
    "SELECT COUNT(*) as count FROM guards_controls gc
     JOIN posts p ON gc.post_id = p.id
     WHERE p.owner_id = ?",
    [$_SESSION['user_id']]
);

// Feedbacks
$stats['feedbacks'] = $db->fetch(
    "SELECT COUNT(*) as count FROM feedback
     WHERE Client = ?",
    [$_SESSION['user_id']]
);

// Total patrols (new patrol system uses post_id)
$stats['patrols'] = $db->fetch(
    "SELECT COUNT(*) as count FROM patrols p
     WHERE p.post_id IN (SELECT id FROM posts WHERE owner_id = ?)",
    [$_SESSION['user_id']]
);

// Invoices
$stats['invoices'] = $db->fetch(
    "SELECT COUNT(*) as count, SUM(total_amount) as total_amount 
     FROM invoices 
     WHERE owner_id = ?",
    [$_SESSION['user_id']]
);

require_once __DIR__ . '/../layouts/header.php';
?>

<div class="container mx-auto px-4 py-8 max-w-7xl">
    <!-- Welcome Section -->
    <div class="mb-8">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-4xl font-bold text-gray-800">
                    <i class="fas fa-home text-blue-600 mr-3"></i>Welcome, <?php echo htmlspecialchars($client['contact_person'] ?? $client['name']); ?>
                </h1>
                <p class="text-gray-600 mt-2">
                    Company: <span class="font-semibold"><?php echo htmlspecialchars($client['company_name'] ?? $client['name']); ?></span> | 
                </p>
            </div>
            <div class="text-right space-y-2">
                <p class="text-sm text-gray-600">Last login</p>
                <p class="text-lg font-semibold text-gray-800"><?php echo date('M d, Y'); ?></p>
                <button id="installAppBtn" class="hidden mt-4 bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition font-semibold flex items-center justify-center gap-2 ml-auto">
                    <i class="fas fa-download"></i>Install App
                </button>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-6 gap-4 mb-8">
        <!-- Guards -->
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-6 rounded-lg border border-blue-200 shadow hover:shadow-lg transition">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">My Guards</p>
                    <p class="text-4xl font-bold text-blue-600 mt-2"><?php echo $stats['guards']['count'] ?? 0; ?></p>
                </div>
                <i class="fas fa-user-shield text-5xl text-blue-200 opacity-50"></i>
            </div>
            <a href="?page=clients/my-guards" class="text-blue-600 hover:text-blue-700 text-sm font-semibold mt-3 inline-block">View All →</a>
        </div>

        <!-- Posts -->
        <div class="bg-gradient-to-br from-green-50 to-green-100 p-6 rounded-lg border border-green-200 shadow hover:shadow-lg transition">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">My Posts</p>
                    <p class="text-4xl font-bold text-green-600 mt-2"><?php echo $stats['posts']['count'] ?? 0; ?></p>
                </div>
                <i class="fas fa-location-dot text-5xl text-green-200 opacity-50"></i>
            </div>
        </div>

        <!-- Controls -->
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-6 rounded-lg border border-purple-200 shadow hover:shadow-lg transition">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Controls</p>
                    <p class="text-4xl font-bold text-purple-600 mt-2"><?php echo $stats['controls']['count'] ?? 0; ?></p>
                </div>
                <i class="fas fa-check-circle text-5xl text-purple-200 opacity-50"></i>
            </div>
            <a href="?page=clients/my-controls" class="text-purple-600 hover:text-purple-700 text-sm font-semibold mt-3 inline-block">View All →</a>
        </div>

        <!-- Feedbacks -->
        <div class="bg-gradient-to-br from-orange-50 to-orange-100 p-6 rounded-lg border border-orange-200 shadow hover:shadow-lg transition">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">My Feedbacks</p>
                    <p class="text-4xl font-bold text-orange-600 mt-2"><?php echo $stats['feedbacks']['count'] ?? 0; ?></p>
                </div>
                <i class="fas fa-comments text-5xl text-orange-200 opacity-50"></i>
            </div>
            <a href="?page=clients/my-feedbacks" class="text-orange-600 hover:text-orange-700 text-sm font-semibold mt-3 inline-block">View All →</a>
        </div>

        <!-- Patrols -->
        <div class="bg-gradient-to-br from-red-50 to-red-100 p-6 rounded-lg border border-red-200 shadow hover:shadow-lg transition">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">My Patrols</p>
                    <p class="text-4xl font-bold text-red-600 mt-2"><?php echo $stats['patrols']['count'] ?? 0; ?></p>
                </div>
                <i class="fas fa-shoe-prints text-5xl text-red-200 opacity-50"></i>
            </div>
            <a href="?page=clients/my-patrols" class="text-red-600 hover:text-red-700 text-sm font-semibold mt-3 inline-block">View All →</a>
        </div>

        <!-- Invoices -->
        <div class="bg-gradient-to-br from-emerald-50 to-emerald-100 p-6 rounded-lg border border-emerald-200 shadow hover:shadow-lg transition">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Invoices</p>
                    <p class="text-4xl font-bold text-emerald-600 mt-2"><?php echo $stats['invoices']['count'] ?? 0; ?></p>
                    <p class="text-xs text-gray-600 mt-1"><?php echo isset($stats['invoices']['total_amount']) ? number_format($stats['invoices']['total_amount'], 0).' FCFA' : ''; ?></p>
                </div>
                <i class="fas fa-file-invoice text-5xl text-emerald-200 opacity-50"></i>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Quick Actions -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-lg shadow border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-xl font-bold text-gray-800">
                        <i class="fas fa-bolt text-blue-600 mr-2"></i>Quick Actions
                    </h2>
                </div>
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <a href="?page=clients/feedbacks" class="px-4 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-star"></i>Give Feedback
                        </a>
                        <a href="?page=clients/payments" class="px-4 py-3 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-money-bill-wave"></i>Make Payment
                        </a>
                        <a href="?page=clients/messages" class="px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-envelope"></i>Send Message
                        </a>
                        <a href="?page=clients/my-patrols" class="px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-shoe-prints"></i>View Patrol Reports
                        </a>
                        <a href="?page=clients/my-controls" class="px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-check-circle"></i>View Control Reports
                        </a>
                        <a href="?page=clients/my-invoices" class="px-4 py-3 bg-cyan-600 text-white rounded-lg hover:bg-cyan-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-file-invoice"></i>View Invoices
                        </a>
                        <a href="?page=clients/contract" class="px-4 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-file-pdf"></i>My Contract
                        </a>
                        <a href="?page=clients/site-assessment" class="px-4 py-3 bg-rose-600 text-white rounded-lg hover:bg-rose-700 font-semibold text-center transition flex items-center justify-center gap-2">
                            <i class="fas fa-file-lines"></i>Site Assessment
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Profile Info -->
        <div>
            <div class="bg-white rounded-lg shadow border border-gray-200 p-6">
                <h3 class="text-lg font-bold text-gray-800 mb-4">
                    <i class="fas fa-building text-blue-600 mr-2"></i>Client Info
                </h3>
                <div class="space-y-3">
                    <div>
                        <p class="text-xs text-gray-600 font-semibold">Client Name</p>
                        <p class="text-gray-800"><?php echo htmlspecialchars($client['company_name'] ?? $client['name']); ?></p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600 font-semibold">Contact Person</p>
                        <p class="text-gray-800"><?php echo htmlspecialchars($client['contact_person'] ?? $client['name']); ?></p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600 font-semibold">Email</p>
                        <p class="text-gray-800"><?php echo htmlspecialchars($client['email']); ?></p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600 font-semibold">Phone</p>
                        <p class="text-gray-800"><?php echo htmlspecialchars($client['phone'] ?? 'N/A'); ?></p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600 font-semibold">Zone</p>
                        <p class="text-gray-800"><?php echo htmlspecialchars($client['zone'] ?? 'N/A'); ?></p>
                    </div>
                    <a href="?page=clients/profile" class="text-blue-600 hover:text-blue-700 text-sm font-semibold mt-4 inline-block">Edit Profile →</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function downloadContract(e) {
    e.preventDefault();
    fetch('?page=api&endpoint=clients/contract-pdf&id=<?php echo $_SESSION['user_id']; ?>')
    .then(res => {
        if (res.ok) return res.blob();
        throw new Error('Failed to download contract');
    })
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'contract_<?php echo $_SESSION['user_id']; ?>.pdf';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
    })
    .catch(err => showToast('error', err.message));
}

function downloadAssessment(e) {
    e.preventDefault();
    fetch('?page=api&endpoint=clients/assessment-pdf&id=<?php echo $_SESSION['user_id']; ?>')
    .then(res => {
        if (res.ok) return res.blob();
        throw new Error('Failed to download assessment');
    })
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'site_assessment_<?php echo $_SESSION['user_id']; ?>.pdf';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
    })
    .catch(err => showToast('error', err.message));
}
</script>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>
