<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Branch Info Controller (Public)
 *
 * Displays an attractive public profile page for a branch at /branch-info/{code}
 * Shows: branch photos, facilities, faculty, courses, gallery, map, about,
 * social links, opening hours, contact info — like a hotel/business listing.
 */
class BranchInfoController extends Controller
{
    /**
     * Show branch public profile page.
     */
    public function show(string $code): void
    {
        $code = trim($code);

        // Try by branch_code first, then by id
        $stmt = $this->db->prepare(
            "SELECT b.* FROM `branches` b
             WHERE b.`branch_code` = :code OR b.`id` = :id
             LIMIT 1"
        );
        $stmt->execute([':code' => $code, ':id' => (int) $code]);
        $branch = $stmt->fetch() ?: null;

        if (!$branch || $branch['status'] === 'suspended') {
            http_response_code(404);
            $this->view('branch_info/not_found', [
                'title'       => 'Branch Not Found',
                'currentPage' => 'home',
            ]);
            return;
        }

        $branchId = (int) $branch['id'];

        // Fetch facilities
        $facilities = [];
        try {
            $stmt = $this->db->prepare("SELECT * FROM `branch_facilities` WHERE `branch_id` = :bid AND `is_available` = 1 ORDER BY `facility_name`");
            $stmt->execute([':bid' => $branchId]);
            $facilities = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {
            // Fallback to JSON in branches.facilities
            if (!empty($branch['facilities'])) {
                $decoded = json_decode($branch['facilities'], true);
                if (is_array($decoded)) {
                    foreach ($decoded as $f) {
                        $facilities[] = ['facility_name' => $f, 'description' => null];
                    }
                }
            }
        }

        // Fetch faculty
        $faculty = [];
        try {
            $stmt = $this->db->prepare("SELECT * FROM `branch_faculty` WHERE `branch_id` = :bid AND `is_active` = 1 ORDER BY `sort_order`");
            $stmt->execute([':bid' => $branchId]);
            $faculty = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // Fetch social links
        $socialLinks = [];
        try {
            $stmt = $this->db->prepare("SELECT * FROM `branch_social_links` WHERE `branch_id` = :bid AND `is_active` = 1");
            $stmt->execute([':bid' => $branchId]);
            $socialLinks = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // Fetch courses offered (from branch_course_fees → courses)
        $courses = [];
        try {
            $stmt = $this->db->prepare(
                "SELECT c.*, bcf.`fee_amount`, bcf.`discount_percentage`
                 FROM `courses` c
                 INNER JOIN `branch_course_fees` bcf ON c.`id` = bcf.`course_id`
                 WHERE bcf.`branch_id` = :bid AND bcf.`is_active` = 1 AND c.`active` = 1
                 ORDER BY c.`name`"
            );
            $stmt->execute([':bid' => $branchId]);
            $courses = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // Fetch reviews
        $reviews = [];
        $avgRating = 0;
        $totalReviews = 0;
        try {
            $stmt = $this->db->prepare(
                "SELECT br.*, u.`name` AS user_name FROM `branch_reviews` br
                 LEFT JOIN `users` u ON br.`user_id` = u.`id`
                 WHERE br.`branch_id` = :bid AND br.`is_approved` = 1
                 ORDER BY br.`created_at` DESC LIMIT 6"
            );
            $stmt->execute([':bid' => $branchId]);
            $reviews = $stmt->fetchAll() ?: [];

            $stmt = $this->db->prepare("SELECT AVG(`rating`) AS avg_rating, COUNT(*) AS total FROM `branch_reviews` WHERE `branch_id` = :bid AND `is_approved` = 1");
            $stmt->execute([':bid' => $branchId]);
            $ratingData = $stmt->fetch();
            $avgRating = round((float) ($ratingData['avg_rating'] ?? 0), 1);
            $totalReviews = (int) ($ratingData['total'] ?? 0);
        } catch (\Throwable $e) {}

        $this->view('branch_info/show', [
            'title'        => ($branch['name'] ?? 'Branch') . ' - Gmind Institute',
            'currentPage'  => 'branch-info',
            'branch'       => $branch,
            'facilities'   => $facilities,
            'faculty'      => $faculty,
            'socialLinks'  => $socialLinks,
            'courses'      => $courses,
            'reviews'      => $reviews,
            'avgRating'    => $avgRating,
            'totalReviews' => $totalReviews,
        ]);
    }
}
