<?php
/**
 * Client - My Posts (Readonly)
 * View all posts with contracts and site assessments
 */

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

// Get current user
$user = $db->fetch("SELECT id, name FROM users WHERE id = ? AND role = 'client'", [$_SESSION['user_id'] ?? 0]);
if (!$user) {
    header('Location: ?page=dashboard');
    exit();
}

// Get user's posts (as facility owner)
$posts = $db->fetchAll(
    "SELECT p.id, p.name, p.facility_type, p.location, p.zone, p.status, p.observations,
            COUNT(DISTINCT gpa.guard_id) as guard_count,
            COUNT(DISTINCT gc.id) as control_count,
            CASE WHEN p.assessment_security_post IS NOT NULL THEN 1 ELSE 0 END as has_assessment
     FROM posts p
     LEFT JOIN guard_post_assignments gpa ON p.id = gpa.post_id
     LEFT JOIN guards_controls gc ON p.id = gc.post_id
     WHERE p.owner_id = ?
     GROUP BY p.id
     ORDER BY p.name",
    [$_SESSION['user_id']]
);

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

<div class="container mx-auto px-4 py-8 max-w-7xl">
    <!-- Header -->
    <div class="mb-8">
        <div class="flex items-center justify-between">
            <h1 class="text-4xl font-bold text-gray-800">
                <i class="fas fa-location-dot text-blue-600 mr-3"></i>My Posts
            </h1>
            <a href="?page=clients/dashboard" class="px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 font-semibold">
                <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
            </a>
        </div>
        <p class="text-gray-600 mt-2">
            Total posts: <span class="font-bold text-blue-600"><?php echo count($posts); ?></span>
        </p>
    </div>

    <!-- Posts Grid - Card Style -->
    <?php if (!empty($posts)): ?>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($posts as $post): ?>
                <div class="bg-white rounded-lg shadow border border-gray-200 hover:shadow-lg transition overflow-hidden">
                    <!-- Post Header -->
                    <div class="bg-gradient-to-r from-blue-600 to-blue-700 p-4 text-white">
                        <h3 class="text-lg font-bold"><?php echo htmlspecialchars($post['name'] ?? 'N/A'); ?></h3>
                        <p class="text-blue-100 text-sm">
                            <i class="fas fa-map-pin mr-1"></i><?php echo htmlspecialchars($post['zone'] ?? 'N/A'); ?>
                        </p>
                    </div>

                    <!-- Post Details -->
                    <div class="p-6 space-y-4">
                        <!-- Description -->
                        <?php if (!empty($post['observations'])): ?>
                            <div>
                                <p class="text-xs text-gray-600 font-semibold mb-1">Observations</p>
                                <p class="text-sm text-gray-700"><?php echo htmlspecialchars(substr($post['observations'], 0, 100)); ?>...</p>
                            </div>
                        <?php endif; ?>

                        <!-- Key Metrics -->
                        <div class="grid grid-cols-3 gap-3 py-3 border-y border-gray-200">
                            <div class="text-center">
                                <p class="text-2xl font-bold text-blue-600"><?php echo $post['guard_count']; ?></p>
                                <p class="text-xs text-gray-600">Guards</p>
                            </div>
                            <div class="text-center">
                                <p class="text-2xl font-bold text-green-600"><?php echo $post['control_count']; ?></p>
                                <p class="text-xs text-gray-600">Controls</p>
                            </div>
                            <div class="text-center">
                                <p class="text-2xl font-bold text-orange-600"><?php echo (!empty($post['has_assessment']) ? '✓' : '-'); ?></p>
                                <p class="text-xs text-gray-600">Assessment</p>
                            </div>
                        </div>

                        <!-- Status -->
                        <div class="flex items-center justify-between">
                            <span class="text-xs text-gray-600">Status</span>
                            <span class="inline-block px-3 py-1 rounded-full text-xs font-semibold <?php 
                                echo (isset($post['status']) && $post['status'] === 'Active') ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700';
                            ?>">
                                <?php echo ucfirst($post['status'] ?? 'N/A'); ?>
                            </span>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex gap-2">
                        <!-- View Contract -->
                        <a href="?page=clients/contract&post_id=<?php echo $post['id']; ?>" class="flex-1 px-3 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 font-semibold transition text-center" title="View contract document">
                            <i class="fas fa-file-pdf mr-1"></i>Contract
                        </a>
                        
                        <!-- View/Download Site Assessment -->
                        <?php if ($post['has_assessment']): ?>
                            <a href="?page=clients/site-assessment&post_id=<?php echo $post['id']; ?>" class="flex-1 px-3 py-2 bg-green-600 text-white rounded text-sm hover:bg-green-700 font-semibold transition text-center" title="View site assessment">
                                <i class="fas fa-download mr-1"></i>Assessment
                            </a>
                        <?php endif; ?>
                        
                        <!-- View Details -->
                        <button onclick="viewPostDetails(<?php echo $post['id']; ?>)" class="flex-1 px-3 py-2 bg-gray-600 text-white rounded text-sm hover:bg-gray-700 font-semibold transition" title="View full details">
                            <i class="fas fa-eye mr-1"></i>Details
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="bg-white rounded-lg shadow border border-gray-200 p-12 text-center">
            <i class="fas fa-inbox text-5xl text-gray-300 mb-4"></i>
            <p class="text-gray-500 text-lg">No posts assigned yet</p>
            <p class="text-gray-400 text-sm mt-2">Your posts will appear here once assigned by an administrator</p>
        </div>
    <?php endif; ?>
</div>

<script>
function viewPostDetails(postId) {
    // Show full post details in modal
    Swal.fire({
        title: 'Loading...',
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    fetch('?page=api&action=get_post&id=' + postId)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    title: data.post.name,
                    html: `
                        <div class="text-left space-y-3">
                            <div>
                                <p class="text-xs text-gray-600 font-semibold">Zone</p>
                                <p class="text-gray-800">${data.post.zone}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-600 font-semibold">Address</p>
                                <p class="text-gray-800">${data.post.address || 'N/A'}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-600 font-semibold">Description</p>
                                <p class="text-gray-800">${data.post.description || 'N/A'}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-600 font-semibold">Status</p>
                                <p class="text-gray-800">${data.post.status}</p>
                            </div>
                        </div>
                    `,
                    icon: 'info',
                    confirmButtonText: 'Close'
                });
            }
        })
        .catch(err => {
            Swal.fire('Error', 'Failed to load post details', 'error');
        });
}
</script>

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