<?php
namespace BranchAdmin\Controllers;

use BranchAdmin\Controllers\BranchAdminController;

class BranchFacilityController extends BranchAdminController
{
    public function index(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        $stmt = $this->db->prepare("SELECT * FROM branches WHERE id = ?");
        $stmt->execute([$branchId]);
        $branch = $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];

        $facilities = [];
        if (!empty($branch['facilities'])) {
            $decoded = json_decode($branch['facilities'], true);
            if (is_array($decoded)) $facilities = $decoded;
        }
        $branch['facilities_list'] = $facilities;

        $facilityOptions = [
            'AC Classrooms', 'WiFi', 'Computer Lab', 'Library', 'Parking',
            'CCTV Surveillance', 'Drinking Water', 'Washroom', 'Projector',
            'Whiteboard', 'Audio System', 'Generator Backup', 'Canteen',
            'Study Room', 'Reception Area', 'Waiting Area',
        ];

        $this->branchAdminView('facilities/index', [
            'title' => 'Branch Facility', 'currentPage' => 'facilities',
            'branch' => $branch, 'facilityOptions' => $facilityOptions,
        ]);
    }

    public function update(): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();

        $ownerName = sanitize($_POST['owner_name'] ?? '');
        $openingTime = sanitize($_POST['opening_time'] ?? '');
        $closingTime = sanitize($_POST['closing_time'] ?? '');
        $runningSince = sanitize($_POST['running_since'] ?? '') ?: null;
        $description = $_POST['description'] ?? '';

        $facilities = $_POST['facilities'] ?? [];
        $facilities = array_map('sanitize', $facilities);
        $facilitiesJson = json_encode($facilities);

        $stmt = $this->db->prepare("SELECT * FROM branches WHERE id = ?");
        $stmt->execute([$branchId]);
        $currentBranch = $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];

        $photoFront = $currentBranch['photo_front'] ?? null;
        $photoBack = $currentBranch['photo_back'] ?? null;
        $photoClass = $currentBranch['photo_class'] ?? null;
        $photoReception = $currentBranch['photo_reception'] ?? null;

        $uploaded = $this->handleImageUpload('photo_front', 'branches');
        if ($uploaded) $photoFront = $uploaded;
        $uploaded = $this->handleImageUpload('photo_back', 'branches');
        if ($uploaded) $photoBack = $uploaded;
        $uploaded = $this->handleImageUpload('photo_class', 'branches');
        if ($uploaded) $photoClass = $uploaded;
        $uploaded = $this->handleImageUpload('photo_reception', 'branches');
        if ($uploaded) $photoReception = $uploaded;

        try {
            $stmt = $this->db->prepare(
                "UPDATE branches SET owner_name=?, opening_time=?, closing_time=?, running_since=?, facilities=?, photo_front=?, photo_back=?, photo_class=?, photo_reception=?, description=?, updated_at=NOW() WHERE id=?"
            );
            $stmt->execute([$ownerName, $openingTime, $closingTime, $runningSince, $facilitiesJson, $photoFront, $photoBack, $photoClass, $photoReception, $description, $branchId]);
            flash('success', 'Branch facility updated successfully.');
        } catch (\Exception $e) {
            flash('error', 'Failed to update facility. ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/branch/facilities');
    }

    public function reviews(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();

        $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 = ? ORDER BY br.created_at DESC");
        $stmt->execute([$branchId]);
        $reviews = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

        $stmt = $this->db->prepare("SELECT COALESCE(AVG(rating), 0) as avg_rating, COUNT(*) as total_reviews FROM branch_reviews WHERE branch_id = ?");
        $stmt->execute([$branchId]);
        $avgData = $stmt->fetch(\PDO::FETCH_ASSOC);

        $this->branchAdminView('facilities/reviews', [
            'title' => 'Branch Reviews', 'currentPage' => 'facilities',
            'reviews' => $reviews, 'avgRating' => (float) ($avgData['avg_rating'] ?? 0),
            'totalReviews' => (int) ($avgData['total_reviews'] ?? 0),
        ]);
    }

    public function approveReview(array $params): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();
        $reviewId = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT * FROM branch_reviews WHERE id = ? AND branch_id = ?");
        $stmt->execute([$reviewId, $branchId]);
        $review = $stmt->fetch(\PDO::FETCH_ASSOC);
        if (!$review) {
            flash('error', 'Review not found.');
            redirect(BASE_PATH . '/branch/facilities/reviews');
            return;
        }

        $newStatus = $review['is_approved'] ? 0 : 1;
        $this->db->prepare("UPDATE branch_reviews SET is_approved = ?, updated_at = NOW() WHERE id = ? AND branch_id = ?")->execute([$newStatus, $reviewId, $branchId]);
        flash('success', 'Review status updated.');
        redirect(BASE_PATH . '/branch/facilities/reviews');
    }

    public function deleteReview(array $params): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        $branchId = $this->getBranchId();
        $reviewId = (int) ($params['id'] ?? 0);

        $this->db->prepare("DELETE FROM branch_reviews WHERE id = ? AND branch_id = ?")->execute([$reviewId, $branchId]);
        flash('success', 'Review deleted successfully.');
        redirect(BASE_PATH . '/branch/facilities/reviews');
    }
}
