<?php
require_once __DIR__ . '/../includes/header.php';

$pdo = db();

$pricingPlans = $pdo->query("
    SELECT *
    FROM plans
    ORDER BY 
        CASE 
            WHEN LOWER(name) = 'trial' THEN 0
            WHEN LOWER(name) = 'starter' THEN 1
            WHEN LOWER(name) = 'growth' THEN 2
            WHEN LOWER(name) = 'pro' THEN 3
            ELSE 4
        END,
        price_gbp ASC
")->fetchAll();

function public_plan_description(array $plan): string
{
    $name = strtolower($plan['name'] ?? '');

    if ($name === 'trial') return 'Try Axenixa before choosing a paid plan';
    if ($name === 'starter') return 'Perfect for freelancers & small agencies';
    if ($name === 'growth') return 'Ideal for growing agencies';
    if ($name === 'pro') return 'For established agencies';

    return 'Flexible plan for your agency';
}

function public_plan_features(array $plan): array
{
    $name = strtolower($plan['name'] ?? '');
    $clientLimit = $plan['client_limit'] ?? null;
    $teamLimit = $plan['team_limit'] ?? null;

    $features = [];

    if ($name === 'trial') {
        $features[] = '3-Day Trial';
        $features[] = 'No Credit Card Required';
    }

    $features[] = $clientLimit && (int)$clientLimit > 0
        ? 'Up to ' . (int)$clientLimit . ' Clients'
        : 'Unlimited Clients';

    $features[] = $teamLimit && (int)$teamLimit > 0
        ? 'Up to ' . (int)$teamLimit . ' Team Members'
        : 'Unlimited Team Members';

    $features[] = 'Client Portal';
    $features[] = 'Project Management';
    $features[] = 'File Sharing';
    $features[] = 'Reviews';

    return $features;
}

$agenciesStmt = $pdo->query("
    SELECT
        a.id,
        a.name,
        a.logo_path,
        a.status,
        COALESCE(ROUND(AVG(pr.rating), 1), 0) AS avg_rating,
        COUNT(pr.id) AS total_reviews,
        (
            SELECT pr2.review
            FROM project_reviews pr2
            WHERE pr2.agency_id = a.id
              AND pr2.is_public = 1
              AND pr2.review IS NOT NULL
              AND pr2.review != ''
            ORDER BY pr2.approved_at DESC, pr2.created_at DESC
            LIMIT 1
        ) AS latest_review
    FROM agencies a
    LEFT JOIN project_reviews pr
        ON pr.agency_id = a.id
       AND pr.is_public = 1
    GROUP BY a.id, a.name, a.logo_path, a.status
    ORDER BY total_reviews DESC, avg_rating DESC, a.created_at DESC
");

$registeredAgencies = $agenciesStmt->fetchAll();

$publicReviews = $pdo->query("
    SELECT
        pr.rating,
        pr.review,
        pr.created_at,
        a.name AS agency_name,
        a.logo_path,
        c.company_name
    FROM project_reviews pr
    JOIN agencies a ON a.id = pr.agency_id
    LEFT JOIN clients c ON c.id = pr.client_id
    WHERE pr.is_public = 1
    ORDER BY pr.approved_at DESC, pr.created_at DESC
    LIMIT 12
")->fetchAll();
?>

<nav class="navbar navbar-expand-lg fixed-top py-2">
    <div class="container" style="height: 80px;">
        <a class="navbar-brand" href="#">
            <img src="<?= APP_URL ?>/assets/img/logo.png" class="lgo" alt="Axenixa" style="width:150px;margin-top:-40px;margin-bottom:-40px;">
        </a>

        <button class="navbar-toggler bg-light" type="button" data-bs-toggle="collapse" data-bs-target="#nav">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="nav">
            <div class="navbar-nav mx-auto gap-lg-4">
                <a class="nav-link text-white" href="#features">Features</a>
                <a class="nav-link text-white" href="#pricing">Pricing</a>
                <a class="nav-link text-white" href="#agencies">Agencies</a>
                <a class="nav-link text-white" href="#how">How It Works</a>
                <a class="nav-link text-white" href="#testimonials">Testimonials</a>
                <a class="nav-link text-white" href="#contact">Contact</a>
            </div>

            <div class="d-flex gap-3">
                <a class="btn btn-outline-light px-4" style="padding:5px 10px;line-height: 32px;border-radius: 5px;font-size: 15px;" href="<?= APP_URL ?>/auth/login.php">Login</a>
                <a class="bt1 btn btn-primary px-4" href="<?= APP_URL ?>/auth/register.php" style="border-radius: 5px;padding: 5px 10px;font-size: 15px;line-height: 32px;">Get Started</a>
            </div>
        </div>
    </div>
</nav>

<section class="hero pt-5">
    <div class="container">
        <div class="row align-items-center g-5">
            <div class="col-lg-5">
                <img src="<?= APP_URL ?>/assets/img/logo.png" class="hero-logo" alt="Axenixa">

                <div class="text-red fw-bold mb-3">THE CLIENT PORTAL BUILT FOR AGENCIES</div>

                <h1 class="display-4 fw-bold">
                    Manage Clients, Projects & Files From <span class="text-red">One Place</span>
                </h1>

                <p class="lead muted mt-3">
                    Axenixa helps agencies deliver a professional client experience, stay organized and grow their business.
                </p>

                <div class="d-flex gap-3 mt-4">
                    <a class="bt1 btn btn-primary btn-lg" href="<?= APP_URL ?>/auth/register.php" style="border-radius: 5px;font-size: 15px;padding: 5px 10px;line-height: 32px;">Start Free Trial →</a>
                    <a class="btn btn-outline-light btn-lg" href="#pricing" style="padding:5px 10px;border-radius: 5px;font-size: 15px;line-height: 32px;">View Demo</a>
                </div>

                <div class="d-flex gap-4 mt-4 flex-wrap muted">
                    <span>✓ No credit card required</span>
                    <span>✓ 3-day free trial</span>
                    <span>✓ Cancel anytime</span>
                </div>
            </div>

            <div class="col-lg-7">
                <div class="mock-dashboard">
                    <div class="d-flex justify-content-between mb-4">
                        <img src="<?= APP_URL ?>/assets/img/logo.png" style="height:54px" alt="Axenixa">
                        <div class="muted tiny">John Doe<br>Acme Agency</div>
                    </div>

                    <h4>Dashboard</h4>

                    <div class="row g-3 my-2">
                        <div class="col-md-3"><div class="metric"><span class="muted tiny">Total Clients</span><h3>24</h3><span class="text-success tiny">↗ 12%</span></div></div>
                        <div class="col-md-3"><div class="metric"><span class="muted tiny">Active Projects</span><h3>18</h3><span class="text-success tiny">↗ 6%</span></div></div>
                        <div class="col-md-3"><div class="metric"><span class="muted tiny">Tasks Completed</span><h3>128</h3><span class="text-success tiny">↗ 15%</span></div></div>
                        <div class="col-md-3"><div class="metric"><span class="muted tiny">Revenue</span><h3>£4,890</h3><span class="text-success tiny">↗ 10%</span></div></div>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-8">
                            <div class="cardx">
                                <strong>Projects Overview</strong>
                                <div style="height:190px" class="d-flex align-items-end gap-2 mt-3">
                                    <?php foreach ([25,35,78,65,48,63,86,82,110] as $h): ?>
                                        <div style="height:<?= $h ?>px;background:linear-gradient(#D91E2E,rgba(217,30,46,.15));width:11%;border-radius:8px 8px 0 0"></div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="cardx">
                                <strong>Recent Activity</strong>
                                <p class="muted tiny mt-3">New project created</p>
                                <p class="muted tiny">File uploaded</p>
                                <p class="muted tiny">New client added</p>
                                <p class="text-red tiny">View all activity →</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
   </div>
</section>

<section id="features" class="py-5">
    <div class="container">
        <div class="text-center mb-4">
            <h2 class="fw-bold">Features Built for Agencies</h2>
            <p class="muted">Everything you need to manage clients from one workspace.</p>
        </div>

        <div class="row g-4">
            <?php foreach ([
                ['Projects', 'Create projects, track progress, deadlines and milestones.'],
                ['Files & Approvals', 'Share files and collect approvals or change requests.'],
                ['Messages', 'Keep client communication organized in one place.'],
                ['Reviews', 'Collect client reviews after completed projects.']
            ] as $feature): ?>
                <div class="col-md-3">
                    <div class="cardx h-100">
                        <h5><?= e($feature[0]) ?></h5>
                        <p class="muted mb-0"><?= e($feature[1]) ?></p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<section id="agencies" class="py-5">
    <div class="container">
        <div class="text-center mb-4">
            <h2 class="fw-bold">Agencies Using Axenixa</h2>
            <p class="muted">See registered agencies and their published client satisfaction ratings.</p>
        </div>

        <?php if (!$registeredAgencies): ?>
            <div class="cardx text-center">
                <p class="muted mb-0">No agencies registered yet.</p>
            </div>
        <?php else: ?>
            <div class="row g-4 justify-content-center">
                <?php foreach ($registeredAgencies as $agency): ?>
                    <?php
                    $logo = !empty($agency['logo_path'])
                        ? APP_URL . $agency['logo_path']
                        : APP_URL . '/assets/img/logo.png';

                    $avgRating = (float)$agency['avg_rating'];
                    $totalReviews = (int)$agency['total_reviews'];
                    $fullStars = (int)floor($avgRating);
                    ?>

                    <div class="col-md-6 col-lg-4">
                        <div class="cardx h-100">
                            <div class="d-flex align-items-center gap-3 mb-3">
                                <div style="width:70px;height:70px;border-radius:18px;background:#111;border:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:center;overflow:hidden;">
                                    <img src="<?= e($logo) ?>" alt="<?= e($agency['name']) ?>" style="max-width:100%;max-height:100%;object-fit:contain;padding:8px;">
                                </div>

                                <div>
                                    <h5 class="mb-1"><?= e($agency['name']) ?></h5>

                                    <?php if ($totalReviews > 0 && $avgRating >= 4.5): ?>
                                        <span class="badge-red rounded-pill px-2 py-1">Top Rated</span>
                                    <?php else: ?>
                                        <span class="tiny muted"><?= e(ucfirst((string)($agency['status'] ?? 'active'))) ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <?php if ($totalReviews > 0): ?>
                                <div class="mb-2" style="font-size:1.1rem;">
                                    <?= str_repeat('⭐', max(0, min(5, $fullStars))) ?>
                                    <span class="muted small"><?= e(number_format($avgRating, 1)) ?>/5</span>
                                </div>

                                <p class="tiny muted mb-2">
                                    <?= $totalReviews ?> published review<?= $totalReviews === 1 ? '' : 's' ?>
                                </p>

                                <?php if (!empty($agency['latest_review'])): ?>
                                    <p class="muted mb-0">
                                        “<?= e(mb_strimwidth($agency['latest_review'], 0, 120, '...')) ?>”
                                    </p>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="mb-2 muted">☆☆☆☆☆</div>
                                <p class="tiny muted mb-0">No published reviews yet.</p>
                            <?php endif; ?>

                            
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<section id="pricing" class="py-5">
    <div class="container">
        <div class="text-center mb-4">
            <h2 class="fw-bold">Simple, Transparent Pricing</h2>
            <p class="muted">Choose the plan that's right for your agency</p>
        </div>

        <?php if (!$pricingPlans): ?>
            <div class="cardx text-center">
                <p class="muted mb-0">No pricing plans are available yet.</p>
            </div>
        <?php else: ?>
            <div class="row g-4 justify-content-center">
                <?php foreach ($pricingPlans as $plan): ?>
                    <?php
                    $planName = $plan['name'] ?? 'Plan';
                    $planNameLower = strtolower($planName);
                    $price = number_format((float)($plan['price_gbp'] ?? 0), 2);
                    $billingText = $planNameLower === 'trial' ? '/3 days' : '/month';
                    $features = public_plan_features($plan);
                    ?>

                    <div class="col-md-4 col-lg-3">
                        <div class="cardx pricing-card <?= $planNameLower === 'growth' ? 'border-danger' : '' ?>">
                            <h3><?= e($planName) ?></h3>

                            <p class="muted tiny">
                                <?= e(public_plan_description($plan)) ?>
                            </p>

                            <div class="price">
                                £<?= e($price) ?>
                                <span class="fs-6 muted"><?= e($billingText) ?></span>
                            </div>

                            <hr>

                            <?php foreach ($features as $feature): ?>
                                <p>🔴 <?= e($feature) ?></p>
                            <?php endforeach; ?>

                            <a href="<?= APP_URL ?>/auth/register.php?plan_id=<?= (int)$plan['id'] ?>" class="bt1 btn btn-primary w-100 mt-2" style="border-radius: 5px;font-size: 15px;line-height: 32px;padding: 5px 10px;">
                                Choose <?= e($planName) ?>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<section id="how" class="py-5">
    <div class="container">
        <div class="text-center mb-4">
            <h2 class="fw-bold">How It Works</h2>
            <p class="muted">Launch your client portal in minutes.</p>
        </div>

        <div class="row g-4">
            <?php foreach ([
                ['1', 'Create your agency account'],
                ['2', 'Invite clients to their portal'],
                ['3', 'Manage projects, files and approvals'],
                ['4', 'Publish client reviews and grow trust']
            ] as $step): ?>
                <div class="col-md-3">
                    <div class="cardx h-100 text-center">
                        <h2 class="text-red"><?= e($step[0]) ?></h2>
                        <p class="muted mb-0"><?= e($step[1]) ?></p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<section id="testimonials" class="py-5">
    <div class="container">
        <div class="text-center mb-4">
            <h2 class="fw-bold">Client Satisfaction</h2>
            <p class="muted">Published reviews from projects managed through Axenixa.</p>
        </div>

        <?php if (!$publicReviews): ?>
            <div class="cardx text-center">
                <h3 class="mb-2">⭐ No public reviews yet</h3>
                <p class="muted mb-0">Approved client reviews will appear here automatically.</p>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($publicReviews as $review): ?>
                    <?php
                    $logo = !empty($review['logo_path'])
                        ? APP_URL . $review['logo_path']
                        : APP_URL . '/assets/img/logo.png';
                    ?>

                    <div class="col-md-6 col-lg-4">
                        <div class="cardx h-100">
                            <div class="d-flex align-items-center gap-3 mb-3">
                                <div style="width:55px;height:55px;border-radius:14px;background:#111;border:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:center;overflow:hidden;">
                                    <img src="<?= e($logo) ?>" alt="<?= e($review['agency_name']) ?>" style="max-width:100%;max-height:100%;object-fit:contain;padding:7px;">
                                </div>

                                <div>
                                    <strong><?= e($review['agency_name']) ?></strong><br>
                                    <span class="tiny muted"><?= e($review['company_name'] ?: 'Client review') ?></span>
                                </div>
                            </div>

                            <div class="mb-2">
                                <?= str_repeat('⭐', (int)$review['rating']) ?>
                            </div>

                            <p class="muted mb-0">
                                “<?= e(mb_strimwidth($review['review'] ?: 'No written feedback.', 0, 160, '...')) ?>”
                            </p>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<footer id="contact" class="footer-section py-5 mt-5" style="background:#0F0F10;border-top:1px solid rgba(255,255,255,.08);">
    <div class="container">
        <div class="row g-5">
            <div class="col-lg-4">
                <img src="<?= APP_URL ?>/assets/img/logo.png" alt="Axenixa" style="height:70px;margin-bottom:15px;">

                <p class="muted">
                    Axenixa helps agencies manage clients, projects, files, communication and approvals from one professional portal.
                </p>

                <p class="tiny muted mb-0">
                    © <?= date('Y') ?> Axenixa. All rights reserved.
                </p>
            </div>

            <div class="col-lg-2">
                <h6 class="fw-bold mb-3">Product</h6>
                <ul class="list-unstyled">
                    <li class="mb-2"><a class="text-decoration-none muted" href="#features">Features</a></li>
                    <li class="mb-2"><a class="text-decoration-none muted" href="#pricing">Pricing</a></li>
                    <li class="mb-2"><a class="text-decoration-none muted" href="<?= APP_URL ?>/auth/register.php">Free Trial</a></li>
                    <li><a class="text-decoration-none muted" href="<?= APP_URL ?>/auth/login.php">Login</a></li>
                </ul>
            </div>

            <div class="col-lg-2">
                <h6 class="fw-bold mb-3">Resources</h6>
                <ul class="list-unstyled">
                    <li class="mb-2"><a class="text-decoration-none muted" href="#how">How It Works</a></li>
                    <li class="mb-2"><a class="text-decoration-none muted" href="#agencies">Agencies</a></li>
                    <li class="mb-2"><a class="text-decoration-none muted" href="#testimonials">Reviews</a></li>
                </ul>
            </div>

            <div class="col-lg-4">
                <h6 class="fw-bold mb-3">Trusted by Agencies</h6>

                <p class="muted">
                    Join agencies already using Axenixa to streamline project delivery and create a better client experience.
                </p>

                <a href="<?= APP_URL ?>/auth/register.php" class="bt1 btn btn-primary" style="padding: 5px 10px;font-size: 15px;border-radius: 5px;line-height: 32px;">
                    Start Your 3-Day Trial
                </a>
                <style>
                    .bt1:hover{
                        background-color: transparent;
                    }
                </style>
            </div>
        </div>

        <hr class="my-4" style="border-color:rgba(255,255,255,.08);">

        <div class="d-flex flex-column flex-md-row justify-content-between align-items-center">
            <p class="tiny muted mb-2 mb-md-0">Built with ❤️ for Agencies</p>

            <div class="d-flex gap-3">
                <div class="footer-links">
    <a href="<?= APP_URL ?>/public/privacy.php" class="tiny muted text-decoration-none" style="margin-left: 5px;">Privacy Policy</a>
    <a href="<?= APP_URL ?>/public/terms.php" class="tiny muted text-decoration-none" style="margin-left: 5px;">Terms of Service</a>
    <a href="<?= APP_URL ?>/public/cookies.php" class="tiny muted text-decoration-none" style="margin-left: 5px;">Cookie Policy</a>
    <a href="<?= APP_URL ?>/public/refund.php" class="tiny muted text-decoration-none" style="margin-left: 5px;">Refund Policy</a>
    <a href="<?= APP_URL ?>/public/acceptable-use.php" class="tiny muted text-decoration-none" style="margin-left: 5px;">Acceptable Use Policy</a>
</div>
                
            </div>
        </div>
    </div>
</footer>

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