<?php
session_start();
require_once __DIR__ . '/config/db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: auth-system/login.php?redirect=service-favorites.php');
    exit;
}

function ensureServiceFavoritesTable(mysqli $connection): bool
{
    $sql = "CREATE TABLE IF NOT EXISTS service_favorites (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        service_id INT NOT NULL,
        service_title VARCHAR(255) NOT NULL,
        service_image VARCHAR(500) NOT NULL,
        service_description TEXT,
        added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_user_service (user_id, service_id),
        INDEX idx_user_id (user_id),
        INDEX idx_service_id (service_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    return (bool) $connection->query($sql);
}

$favorites = [];
$userId = (int) $_SESSION['user_id'];

if (ensureServiceFavoritesTable($connection)) {
    $stmt = $connection->prepare("
        SELECT service_id, service_title, service_image, service_description, added_at
        FROM service_favorites
        WHERE user_id = ?
        ORDER BY added_at DESC
    ");
    if ($stmt) {
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($result && $row = $result->fetch_assoc()) {
            $favorites[] = $row;
        }
        $stmt->close();
    }
}
?>
<!doctype html>
<html class="no-js" lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Favorite Services | Faren Interior Design</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.min.css">
    <link rel="stylesheet" href="assets/css/swiper-bundle.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <script src="assets/js/auth-ui-global.js"></script>
    <style>
        :root {
            --fav-ink: #1e1914;
            --fav-muted: #6f665c;
            --fav-accent: #b58a5a;
            --fav-accent-dark: #8a643f;
            --fav-border: #e7dbce;
            --fav-surface: #ffffff;
        }

        .favorites-page {
            background:
                radial-gradient(circle at 10% 16%, rgba(181, 138, 90, 0.18), transparent 36%),
                radial-gradient(circle at 90% 82%, rgba(131, 98, 66, 0.12), transparent 35%),
                linear-gradient(180deg, #f8f4ee 0%, #f3ece4 100%);
            padding: clamp(90px, 9vw, 145px) 0 clamp(60px, 7vw, 110px);
            min-height: 72vh;
        }

        .favorites-shell {
            max-width: 1180px;
            margin: 0 auto;
            padding: 0 16px;
        }

        .favorites-head {
            border: 1px solid var(--fav-border);
            border-radius: 20px;
            background: var(--fav-surface);
            box-shadow: 0 16px 36px rgba(33, 24, 16, 0.08);
            padding: clamp(18px, 3vw, 30px);
            display: flex;
            justify-content: space-between;
            gap: 16px;
            flex-wrap: wrap;
            margin-bottom: 22px;
        }

        .favorites-head h1 {
            margin: 0;
            color: var(--fav-ink);
            font-size: clamp(30px, 5vw, 46px);
            line-height: 1.1;
        }

        .favorites-head p {
            margin: 10px 0 0;
            color: var(--fav-muted);
            font-size: 15px;
        }

        .head-btn {
            border-radius: 11px;
            text-decoration: none;
            font-size: 13px;
            font-weight: 700;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            padding: 11px 14px;
            color: #fff;
            background: linear-gradient(135deg, var(--fav-accent), var(--fav-accent-dark));
            align-self: center;
        }

        .favorites-grid {
            display: grid;
            grid-template-columns: repeat(12, minmax(0, 1fr));
            gap: clamp(12px, 2vw, 20px);
        }

        .favorite-card {
            grid-column: span 4;
            border: 1px solid var(--fav-border);
            border-radius: 16px;
            background: var(--fav-surface);
            overflow: hidden;
            box-shadow: 0 12px 30px rgba(33, 24, 16, 0.08);
            display: flex;
            flex-direction: column;
        }

        .favorite-image {
            aspect-ratio: 16 / 10;
            background: #ece2d6;
            overflow: hidden;
        }

        .favorite-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .favorite-body {
            padding: 15px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            flex-grow: 1;
        }

        .favorite-title {
            margin: 0;
            font-size: 23px;
            line-height: 1.2;
        }

        .favorite-title a {
            color: var(--fav-ink);
            text-decoration: none;
        }

        .favorite-text {
            margin: 0;
            color: var(--fav-muted);
            font-size: 14px;
            line-height: 1.62;
            flex-grow: 1;
        }

        .favorite-actions {
            display: flex;
            gap: 9px;
            flex-wrap: wrap;
        }

        .fav-btn {
            border-radius: 10px;
            border: 1px solid var(--fav-border);
            background: #faf5ee;
            color: var(--fav-accent-dark);
            text-decoration: none;
            font-size: 13px;
            font-weight: 700;
            padding: 10px 12px;
            cursor: pointer;
        }

        .fav-btn.remove {
            color: #fff;
            border-color: #be4f4f;
            background: #be4f4f;
        }

        .empty-state {
            border: 1px dashed #d6c4b1;
            border-radius: 16px;
            background: #fff;
            text-align: center;
            padding: clamp(26px, 5vw, 46px);
            color: var(--fav-muted);
        }

        .empty-state i {
            font-size: 34px;
            color: var(--fav-accent-dark);
            margin-bottom: 10px;
        }

        .empty-state h2 {
            margin: 0;
            font-size: clamp(24px, 4vw, 34px);
            color: var(--fav-ink);
        }

        .empty-state p {
            margin: 10px auto 18px;
            max-width: 62ch;
            font-size: 15px;
        }

        .toast-fav {
            position: fixed;
            top: 16px;
            right: 16px;
            padding: 10px 13px;
            border-radius: 9px;
            background: #1f1b17;
            color: #fff;
            font-size: 13px;
            z-index: 12000;
            display: none;
        }

        @media (max-width: 1024px) {
            .favorite-card {
                grid-column: span 6;
            }
        }

        @media (max-width: 767.98px) {
            .favorites-page {
                padding-top: 82px;
            }

            .favorite-card {
                grid-column: span 12;
            }
        }

        @media (max-width: 575.98px) {
            .favorites-page {
                padding-top: 70px;
            }

            .favorites-head,
            .favorite-card,
            .empty-state {
                border-radius: 12px;
            }
        }
    </style>
</head>

<body id="show-grid">
    <?php include 'header-php.php'; ?>

    <main class="favorites-page">
        <div class="favorites-shell">
            <section class="favorites-head">
                <div>
                    <h1>Favorite Services</h1>
                    <p>All services you marked as favorites appear here for quick comparison and access.</p>
                </div>
                <a href="service.php" class="head-btn">Back to Services</a>
            </section>

            <?php if (empty($favorites)): ?>
                <section class="empty-state">
                    <i class="fa-solid fa-heart"></i>
                    <h2>No favorite services yet</h2>
                    <p>Go to services and tap the heart icon on any service card to save it here.</p>
                    <a href="service.php" class="head-btn">Browse Services</a>
                </section>
            <?php else: ?>
                <section class="favorites-grid">
                    <?php foreach ($favorites as $item): ?>
                        <?php
                        $serviceId = (int) $item['service_id'];
                        $title = htmlspecialchars((string) $item['service_title']);
                        $image = htmlspecialchars((string) $item['service_image']);
                        $description = htmlspecialchars((string) ($item['service_description'] ?? ''));
                        $detailsLink = 'service-details.php?id=' . $serviceId;
                        ?>
                        <article class="favorite-card" id="favorite-card-<?php echo $serviceId; ?>">
                            <div class="favorite-image">
                                <img src="<?php echo $image; ?>" alt="<?php echo $title; ?>" loading="lazy">
                            </div>
                            <div class="favorite-body">
                                <h2 class="favorite-title"><a href="<?php echo $detailsLink; ?>"><?php echo $title; ?></a></h2>
                                <p class="favorite-text"><?php echo $description; ?></p>
                                <div class="favorite-actions">
                                    <a class="fav-btn" href="<?php echo $detailsLink; ?>">View Details</a>
                                    <button class="fav-btn remove" type="button" data-service-id="<?php echo $serviceId; ?>">Remove</button>
                                </div>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </section>
            <?php endif; ?>
        </div>
    </main>

    <?php include 'footer-section.html'; ?>

    <div class="toast-fav" id="toast-fav"></div>

    <script src="assets/js/vendor/jquery-3.7.1.min.js"></script>
    <script src="assets/js/swiper-bundle.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/jquery.magnific-popup.min.js"></script>
    <script src="assets/js/jquery.counterup.min.js"></script>
    <script src="assets/js/circle-progress.js"></script>
    <script src="assets/js/jquery-ui.min.js"></script>
    <script src="assets/js/imagesloaded.pkgd.min.js"></script>
    <script src="assets/js/isotope.pkgd.min.js"></script>
    <script src="assets/js/nice-select.min.js"></script>
    <script src="assets/js/wow.min.js"></script>
    <script src="assets/js/threesixty.min.js"></script>
    <script src="assets/js/panolens.min.js"></script>
    <script src="assets/js/gsap.min.js"></script>
    <script src="assets/js/ScrollTrigger.min.js"></script>
    <script src="assets/js/SplitText.js"></script>
    <script src="assets/js/SplitType.js"></script>
    <script src="assets/js/lenis.min.js"></script>
    <script src="assets/js/CustomEase.min.js"></script>
    <script src="assets/js/main.js"></script>
    <script>
        (function () {
            function showToast(message) {
                var toast = document.getElementById('toast-fav');
                if (!toast) return;
                toast.textContent = message;
                toast.style.display = 'block';
                setTimeout(function () {
                    toast.style.display = 'none';
                }, 1800);
            }

            document.querySelectorAll('.fav-btn.remove').forEach(function (button) {
                button.addEventListener('click', async function () {
                    var serviceId = this.getAttribute('data-service-id');
                    this.disabled = true;
                    try {
                        var response = await fetch('api/service-favorites-api.php?action=remove', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ service_id: serviceId })
                        });
                        var data = await response.json();
                        if (data.success) {
                            var card = document.getElementById('favorite-card-' + serviceId);
                            if (card) card.remove();
                            showToast('Removed from favorite services');
                            if (document.querySelectorAll('.favorite-card').length === 0) {
                                window.location.reload();
                            }
                        } else {
                            showToast(data.message || 'Unable to remove');
                        }
                    } catch (error) {
                        showToast('Network error while removing');
                    } finally {
                        this.disabled = false;
                    }
                });
            });
        })();
    </script>
</body>

</html>
