<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

function h(?string $s): string
{
    return htmlspecialchars((string) $s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

function asset(string $path): string
{
    $path = ltrim($path, '/');
    return $path;
}

/**
 * @return array<string, string>
 */
function settings_all(): array
{
    try {
        $st = db()->query('SELECT setting_key, setting_value FROM site_settings');
        $rows = $st->fetchAll(PDO::FETCH_KEY_PAIR);
        return is_array($rows) ? $rows : [];
    } catch (Throwable $e) {
        return [];
    }
}

function setting(string $key, string $default = ''): string
{
    static $cache = null;
    if ($cache === null) {
        $cache = settings_all();
    }
    return $cache[$key] ?? $default;
}

function refresh_settings_cache(): void
{
    // noop placeholder; settings_all uses static in setting() — clear by re-query
}

/** @return array<int, array<string, mixed>> */
function banners_active(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM banners WHERE is_active = 1 ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

/** @return array<int, array<string, mixed>> */
function services_all(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM services ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

/** @return array<int, array<string, mixed>> */
function projects_all(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM projects ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

function project_by_slug(string $slug): ?array
{
    try {
        $st = db()->prepare('SELECT * FROM projects WHERE slug = ? LIMIT 1');
        $st->execute([$slug]);
        $row = $st->fetch();
        return $row ?: null;
    } catch (Throwable $e) {
        return null;
    }
}

function service_by_slug(string $slug): ?array
{
    try {
        $st = db()->prepare('SELECT * FROM services WHERE slug = ? LIMIT 1');
        $st->execute([$slug]);
        $row = $st->fetch();
        return $row ?: null;
    } catch (Throwable $e) {
        return null;
    }
}

/** @return array<int, array<string, mixed>> */
function clients_all(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM clients ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

/** @return array<int, array<string, mixed>> */
function team_all(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM team_members ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

/** @return array<int, array<string, mixed>> */
function testimonials_all(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM testimonials ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

/** @return array<int, array<string, mixed>> */
function faqs_all(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM faqs ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

/**
 * Home page pricing cards with nested feature lines (from `pricing_plans` / `pricing_features`).
 *
 * @return list<array<string, mixed>>
 */
function pricing_plans_for_home(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM pricing_plans WHERE is_active = 1 ORDER BY sort_order ASC, id ASC'
        );
        $plans = $st->fetchAll() ?: [];
        if ($plans === []) {
            return [];
        }
        $ids = array_map(static fn (array $p): int => (int) $p['id'], $plans);
        if ($ids === []) {
            return [];
        }
        $in = implode(',', array_fill(0, count($ids), '?'));
        $fs = db()->prepare(
            "SELECT * FROM pricing_features WHERE plan_id IN ($in) ORDER BY plan_id, sort_order ASC, id ASC"
        );
        $fs->execute($ids);
        $rows = $fs->fetchAll() ?: [];
        $byPlan = [];
        foreach ($rows as $r) {
            $pid = (int) $r['plan_id'];
            if (!isset($byPlan[$pid])) {
                $byPlan[$pid] = [];
            }
            $byPlan[$pid][] = $r;
        }
        foreach ($plans as &$p) {
            $pid = (int) $p['id'];
            $p['features'] = $byPlan[$pid] ?? [];
        }
        unset($p);

        return $plans;
    } catch (Throwable $e) {
        return [];
    }
}

/** Active job openings for the public careers page (inactive rows hidden).
 * @return array<int, array<string, mixed>>
 */
function job_openings_active(): array
{
    try {
        $st = db()->query(
            'SELECT * FROM job_openings WHERE is_active = 1 ORDER BY sort_order ASC, id ASC'
        );
        return $st->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

function static_page(string $slug): ?array
{
    try {
        $st = db()->prepare('SELECT * FROM static_pages WHERE slug = ? LIMIT 1');
        $st->execute([$slug]);
        $row = $st->fetch();
        return $row ?: null;
    } catch (Throwable $e) {
        return null;
    }
}

/**
 * Resolve image path: uploads or theme asset
 */
function img_url(?string $path, string $fallback = 'assets/img/about/ab-img-3-1.jpg'): string
{
    $path = trim((string) $path);
    if ($path === '') {
        return $fallback;
    }
    if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
        return $path;
    }
    return $path;
}

/**
 * Template hero slides when no rows in `banners` (matches index.html).
 *
 * @return list<array<string, mixed>>
 */
function home_default_banners(): array
{
    $sub = 'Solar panel solutions have earned us the highest praise in kinds customer reviews. Our community trusts us for a brighter, any sustainable future.';
    return [
        [
            'title' => 'The Best Solar Panels Solutions for',
            'highlight_html' => '<span class="theme-text1">Homeowners</span>',
            'subtitle' => $sub,
            'is_video' => 0,
            'video_path' => null,
            'image_path' => 'assets/img/bg/slider-bg-2-1.jpg',
            'thumb' => ['type' => 'image', 'src' => 'assets/img/slider/slider-sm-2-1.jpg'],
        ],
        [
            'title' => 'Top-Rated Solar Energy Systems for',
            'highlight_html' => '<span class="theme-text1">Modern Homes</span>',
            'subtitle' => $sub,
            'is_video' => 0,
            'video_path' => null,
            'image_path' => 'assets/img/bg/slider-bg-2-2.jpg',
            'thumb' => ['type' => 'image', 'src' => 'assets/img/slider/slider-sm-2-2.jpg'],
        ],
        [
            'title' => 'Smart Solar Power Solutions for',
            'highlight_html' => '<span class="theme-text1">Every Household</span>',
            'subtitle' => $sub,
            'is_video' => 1,
            'video_path' => 'assets/img/slider/solar.mp4',
            'image_path' => null,
            'thumb' => ['type' => 'video', 'src' => 'assets/img/slider/solar.mp4'],
        ],
        [
            'title' => 'Affordable Solar Panel Options for',
            'highlight_html' => '<span class="theme-text1">Easy Living</span>',
            'subtitle' => $sub,
            'is_video' => 0,
            'video_path' => null,
            'image_path' => 'assets/img/bg/slider-bg-2-1.jpg',
            'thumb' => ['type' => 'image', 'src' => 'assets/img/slider/slider-sm-2-1.jpg'],
        ],
        [
            'title' => 'Advanced Solar Energy Solutions for',
            'highlight_html' => '<span class="theme-text1">Residential Use</span>',
            'subtitle' => $sub,
            'is_video' => 0,
            'video_path' => null,
            'image_path' => 'assets/img/bg/slider-bg-2-2.jpg',
            'thumb' => ['type' => 'image', 'src' => 'assets/img/slider/slider-sm-2-2.jpg'],
        ],
        [
            'title' => 'Smart Solar Power Solutions for',
            'highlight_html' => '<span class="theme-text1">Every Household</span>',
            'subtitle' => $sub,
            'is_video' => 1,
            'video_path' => 'assets/img/slider/solar.mp4',
            'image_path' => null,
            'thumb' => ['type' => 'video', 'src' => 'assets/img/slider/solar.mp4'],
        ],
    ];
}

/** Echo hero thumbnail markup for one banner row (matches index.html tab strip). */
function home_hero_thumb_markup(array $b): void
{
    $preset = $b['thumb'] ?? null;
    if (is_array($preset)) {
        if (($preset['type'] ?? '') === 'video') {
            $src = trim((string)($preset['src'] ?? ''));
            if ($src !== '') {
                echo '<video autoplay loop muted><source src="' . h(img_url($src)) . '" type="video/mp4"></video>';
            }
            return;
        }
        if (($preset['type'] ?? '') === 'image') {
            $src = trim((string)($preset['src'] ?? ''));
            if ($src !== '') {
                echo '<img src="' . h(img_url($src)) . '" alt="image">';
            }
            return;
        }
    }
    $vp = trim((string)($b['video_path'] ?? ''));
    if (!empty($b['is_video']) && $vp !== '') {
        $mime = match (true) {
            str_ends_with(strtolower($vp), '.webm') => 'video/webm',
            str_ends_with(strtolower($vp), '.ogv') => 'video/ogg',
            default => 'video/mp4',
        };
        echo '<video autoplay loop muted><source src="' . h($vp) . '" type="' . h($mime) . '"></video>';
        return;
    }
    echo '<img src="' . h(img_url($b['image_path'] ?? null)) . '" alt="image">';
}

/**
 * Build wa.me link with a pre-filled message for a home pricing plan.
 *
 * @param array<string, mixed> $plan Row from `pricing_plans` with nested `features`
 */
function pricing_whatsapp_inquiry_url(array $plan): string
{
    $raw = (string) setting('whatsapp_pricing_phone', '919771249046');
    $phone = preg_replace('/\D+/', '', $raw) ?? '';
    if ($phone === '') {
        $phone = '919771249046';
    }
    $company = (string) setting('company_name', SITE_NAME);
    $title = trim((string) ($plan['card_title'] ?? 'Solar service'));
    $pname = trim((string) ($plan['plan_name'] ?? 'Plan'));
    $price = trim((string) ($plan['price_display'] ?? ''));
    $lines = [
        'Hello! I am interested in a solar service package on your website (' . $company . ').',
        '',
        'Package: ' . $title,
        'Plan: ' . $pname,
    ];
    if ($price !== '') {
        $lines[] = 'Indicative price: ' . $price;
    }
    $feats = $plan['features'] ?? null;
    if (is_array($feats) && $feats !== []) {
        $lines[] = '';
        $lines[] = 'Includes:';
        foreach ($feats as $f) {
            if (!is_array($f)) {
                continue;
            }
            $lab = trim((string) ($f['label'] ?? ''));
            if ($lab === '') {
                continue;
            }
            $lines[] = '• ' . $lab;
        }
    }
    $lines[] = '';
    $lines[] = 'Please share the next steps. Thank you!';

    return 'https://wa.me/' . $phone . '?text=' . rawurlencode(implode("\n", $lines));
}

function csrf_token(): string
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    if (empty($_SESSION['_csrf'])) {
        $_SESSION['_csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['_csrf'];
}

function slugify(string $text): string
{
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    $text = trim((string)$text, '-');
    return $text !== '' ? $text : 'item';
}

function csrf_verify(?string $token): bool
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    return is_string($token) && isset($_SESSION['_csrf']) && hash_equals($_SESSION['_csrf'], $token);
}
