<?php
/**
 * Category Detail Page
 * Displays all listings in a specific category with filtering and pagination
 * Version: 1.0.0
 * Developer: SolutionJunction.in
 */

require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/session.php';
require_once '../../includes/functions.php';

Session::start();

// Get category slug from URL
$category_slug = isset($_GET['category']) ? sanitize($_GET['category']) : null;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);

if (!$category_slug) {
    redirect('/');
}

$db = Database::getInstance();

// Fetch category data
$category = $db->fetchOne(
    "SELECT * FROM " . TBL_CATEGORIES . " WHERE slug = ?",
    [$category_slug]
);

if (!$category) {
    redirect('/');
}

// Count total approved listings in this category
$total_listings = $db->count(
    TBL_LISTINGS,
    "category_id = ? AND status = 'approved'",
    [$category['id']]
);

// Pagination
$items_per_page = 12;
$pagination = paginate($total_listings, $items_per_page, $page);

// Fetch listings for this page
$listings = $db->fetchAll(
    "SELECT * FROM " . TBL_LISTINGS . "
     WHERE category_id = ? AND status = 'approved'
     ORDER BY is_featured DESC, created_at DESC
     LIMIT ?, ?",
    [$category['id'], $pagination['offset'], $items_per_page]
);

// Get all categories for sidebar
$all_categories = $db->fetchAll(
    "SELECT id, name, slug, icon,
            (SELECT COUNT(*) FROM " . TBL_LISTINGS . " WHERE category_id = " . TBL_CATEGORIES . ".id AND status = 'approved') as listing_count
     FROM " . TBL_CATEGORIES . "
     ORDER BY name ASC"
);

include '../includes/header.php';
?>

<div class="container-fluid py-5" style="background: linear-gradient(135deg, #0B6B57 0%, #074a3d 100%);">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-8">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb breadcrumb-light mb-3">
                        <li class="breadcrumb-item"><a href="/" style="color: rgba(255,255,255,0.8);">Home</a></li>
                        <li class="breadcrumb-item active" style="color: #D4941F;">
                            <?php echo escape($category['name']); ?>
                        </li>
                    </ol>
                </nav>
                <h1 class="text-white mb-2" style="font-size: 3rem; font-weight: 700;">
                    <i class="fas fa-<?php echo escape($category['icon']); ?> me-3" style="color: #D4941F;"></i>
                    <?php echo escape($category['name']); ?>
                </h1>
                <p class="text-white" style="font-size: 1.1rem; opacity: 0.95;">
                    <?php echo escape($category['meta_description'] ?? 'Browse all businesses in this category'); ?>
                </p>
                <p class="text-white" style="font-size: 0.95rem; opacity: 0.8;">
                    <i class="fas fa-store me-2"></i>
                    <?php echo $total_listings; ?> Business<?php echo $total_listings !== 1 ? 'es' : ''; ?> Found
                </p>
            </div>
            <div class="col-lg-4 text-center">
                <img src="https://via.placeholder.com/300x200/0B6B57/ffffff?text=<?php echo urlencode($category['name']); ?>" 
                     alt="<?php echo escape($category['name']); ?>" 
                     class="img-fluid rounded" 
                     style="max-width: 100%; height: auto; opacity: 0.9;">
            </div>
        </div>
    </div>
</div>

<div class="container-fluid py-5">
    <div class="container">
        <div class="row">
            <!-- Main Content -->
            <div class="col-lg-9 mb-5">
                <?php if ($total_listings > 0): ?>
                    <!-- Listings Grid -->
                    <div class="row g-4 mb-5">
                        <?php foreach ($listings as $listing): ?>
                            <div class="col-md-6 col-lg-4">
                                <div class="card h-100 shadow-sm hover-shadow" style="transition: all 0.3s ease; border: none;">
                                    <div style="height: 180px; background: linear-gradient(135deg, #0B6B57 0%, #D4941F 100%); display: flex; align-items: center; justify-content: center; color: white; overflow: hidden;">
                                        <?php if ($listing['image']): ?>
                                            <img src="<?php echo escape($listing['image']); ?>" 
                                                 alt="<?php echo escape($listing['name']); ?>" 
                                                 class="w-100 h-100 object-fit-cover">
                                        <?php else: ?>
                                            <div style="font-size: 3rem;">
                                                <i class="fas fa-<?php echo escape($category['icon']); ?>"></i>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-2">
                                            <?php if ($listing['is_featured']): ?>
                                                <span class="badge bg-warning text-dark">
                                                    <i class="fas fa-star"></i> Featured
                                                </span>
                                            <?php endif; ?>
                                            <span class="badge bg-info ms-1">
                                                <?php 
                                                $district = $db->fetchOne("SELECT name FROM " . TBL_DISTRICTS . " WHERE id = ?", [$listing['district_id']]);
                                                echo escape($district['name'] ?? 'N/A');
                                                ?>
                                            </span>
                                        </div>
                                        <h5 class="card-title" style="color: #18352E;">
                                            <?php echo escape($listing['name']); ?>
                                        </h5>
                                        <p class="card-text text-muted small">
                                            <?php echo truncate(escape($listing['description']), 80); ?>
                                        </p>
                                        <div class="mb-3 small">
                                            <div class="mb-1">
                                                <i class="fas fa-map-marker-alt" style="color: #0B6B57;"></i>
                                                <?php echo escape(truncate($listing['address'], 40)); ?>
                                            </div>
                                            <div class="mb-1">
                                                <i class="fas fa-phone" style="color: #0B6B57;"></i>
                                                <a href="tel:<?php echo escape($listing['phone']); ?>" 
                                                   style="color: #0B6B57; text-decoration: none;">
                                                    <?php echo escape($listing['phone']); ?>
                                                </a>
                                            </div>
                                            <div>
                                                <i class="fas fa-envelope" style="color: #0B6B57;"></i>
                                                <a href="mailto:<?php echo escape($listing['email']); ?>" 
                                                   style="color: #0B6B57; text-decoration: none;">
                                                    <?php echo truncate(escape($listing['email']), 30); ?>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-footer bg-white border-0 pt-0">
                                        <a href="/listing/<?php echo $listing['id']; ?>" 
                                           class="btn btn-sm w-100" 
                                           style="background: #0B6B57; color: white; border: none;">
                                            <i class="fas fa-arrow-right me-1"></i> View Details
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Pagination -->
                    <?php if ($pagination['total_pages'] > 1): ?>
                        <nav aria-label="Page navigation" class="mb-5">
                            <ul class="pagination justify-content-center">
                                <?php if ($pagination['has_prev']): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?category=<?php echo urlencode($category_slug); ?>&page=<?php echo $page - 1; ?>">
                                            Previous
                                        </a>
                                    </li>
                                <?php else: ?>
                                    <li class="page-item disabled">
                                        <span class="page-link">Previous</span>
                                    </li>
                                <?php endif; ?>

                                <?php
                                $start_page = max(1, $page - 2);
                                $end_page = min($pagination['total_pages'], $page + 2);
                                
                                if ($start_page > 1):
                                    ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?category=<?php echo urlencode($category_slug); ?>&page=1">1</a>
                                    </li>
                                    <?php if ($start_page > 2): ?>
                                        <li class="page-item disabled"><span class="page-link">...</span></li>
                                    <?php endif;
                                endif;

                                for ($i = $start_page; $i <= $end_page; $i++):
                                    if ($i == $page):
                                        ?>
                                        <li class="page-item active">
                                            <span class="page-link"><?php echo $i; ?></span>
                                        </li>
                                        <?php
                                    else:
                                        ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?category=<?php echo urlencode($category_slug); ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                        </li>
                                        <?php
                                    endif;
                                endfor;

                                if ($end_page < $pagination['total_pages']):
                                    if ($end_page < $pagination['total_pages'] - 1):
                                        ?>
                                        <li class="page-item disabled"><span class="page-link">...</span></li>
                                        <?php
                                    endif;
                                    ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?category=<?php echo urlencode($category_slug); ?>&page=<?php echo $pagination['total_pages']; ?>">
                                            <?php echo $pagination['total_pages']; ?>
                                        </a>
                                    </li>
                                    <?php
                                endif;
                                ?>

                                <?php if ($pagination['has_next']): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?category=<?php echo urlencode($category_slug); ?>&page=<?php echo $page + 1; ?>">
                                            Next
                                        </a>
                                    </li>
                                <?php else: ?>
                                    <li class="page-item disabled">
                                        <span class="page-link">Next</span>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="alert alert-info text-center py-5">
                        <i class="fas fa-info-circle me-2" style="font-size: 2rem;"></i>
                        <h4 class="mt-3">No Listings Found</h4>
                        <p class="mb-3">There are currently no businesses in the "<?php echo escape($category['name']); ?>" category.</p>
                        <a href="/" class="btn btn-sm" style="background: #0B6B57; color: white;">
                            <i class="fas fa-home me-1"></i> Back to Home
                        </a>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-3">
                <!-- Categories Widget -->
                <div class="card shadow-sm mb-4" style="border: none; border-left: 4px solid #0B6B57;">
                    <div class="card-header bg-white border-0" style="border-bottom: 1px solid #eee;">
                        <h6 class="mb-0" style="color: #18352E; font-weight: 700;">
                            <i class="fas fa-list me-2" style="color: #0B6B57;"></i> Browse Categories
                        </h6>
                    </div>
                    <div class="card-body p-0">
                        <div class="list-group list-group-flush">
                            <?php foreach ($all_categories as $cat): ?>
                                <a href="?category=<?php echo urlencode($cat['slug']); ?>" 
                                   class="list-group-item list-group-item-action <?php echo $cat['id'] === $category['id'] ? 'active' : ''; ?>"
                                   style="<?php echo $cat['id'] === $category['id'] ? 'background: #0B6B57; color: white;' : ''; ?>">
                                    <i class="fas fa-<?php echo escape($cat['icon']); ?> me-2"></i>
                                    <?php echo escape($cat['name']); ?>
                                    <span class="badge <?php echo $cat['id'] === $category['id'] ? 'bg-light text-dark' : 'bg-light text-muted'; ?> ms-2">
                                        <?php echo $cat['listing_count']; ?>
                                    </span>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Info Card -->
                <div class="card shadow-sm" style="border: none; background: linear-gradient(135deg, #0B6B57 0%, #074a3d 100%); color: white;">
                    <div class="card-body">
                        <h6 class="card-title" style="color: #D4941F; font-weight: 700;">
                            <i class="fas fa-lightbulb me-2"></i> Need to Add Your Business?
                        </h6>
                        <p class="card-text small mb-3">
                            Submit your business details to the <?php echo escape($category['name']); ?> category and reach more customers.
                        </p>
                        <a href="/submit-listing" class="btn btn-sm btn-light w-100">
                            <i class="fas fa-plus me-1"></i> Submit Business
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Set meta tags for SEO
$page_title = escape($category['name']) . " | Jharkhand Directory";
$page_description = escape($category['meta_description'] ?? $category['name'] . " businesses and services in Jharkhand");
?>

<?php include '../../includes/footer.php'; ?>

<style>
    .breadcrumb-light {
        background-color: transparent;
    }

    .breadcrumb-light .breadcrumb-item a {
        text-decoration: none;
    }

    .breadcrumb-light .breadcrumb-item a:hover {
        text-decoration: underline;
    }

    .hover-shadow {
        cursor: pointer;
    }

    .hover-shadow:hover {
        box-shadow: 0 0.75rem 1.5rem rgba(11, 107, 87, 0.15) !important;
        transform: translateY(-5px);
    }

    .object-fit-cover {
        object-fit: cover;
    }

    .pagination .page-link {
        color: #0B6B57;
        border-color: #ddd;
    }

    .pagination .page-link:hover {
        background-color: #0B6B57;
        color: white;
        border-color: #0B6B57;
    }

    .pagination .page-item.active .page-link {
        background-color: #0B6B57;
        border-color: #0B6B57;
    }

    .list-group-item.active {
        background-color: #0B6B57 !important;
        border-color: #0B6B57 !important;
    }

    .list-group-item {
        border-left: 3px solid transparent;
        transition: all 0.2s ease;
    }

    .list-group-item:hover {
        border-left-color: #0B6B57;
        padding-left: calc(1rem + 2px);
    }
</style>
