<?php

declare(strict_types=1);

namespace BranchAdmin\Controllers;

/**
 * Branch Profile Controller
 *
 * Allows a branch admin to view and update their own branch's public profile
 * (shown on the website at /branch/{code} in Phase 6).
 *
 * Fields: name, owner_name, phone, address, city, state, pincode, map_link,
 *         latitude, longitude, opening_time, closing_time, running_since,
 *         description, facilities, photo_front/back/class/reception, image (logo).
 *
 * NOTE: branch_code, branch_admin_user, wallet_balance, status, rank etc.
 * are SUPER ADMIN-ONLY fields — branch admin cannot change them.
 */
class BranchProfileController extends BranchBaseController
{
    /**
     * View & edit branch profile (single page with form).
     */
    public function index(): void
    {
        requireBranchAdmin();

        $branchId = $this->getBranchId();

        // Fetch branch data
        $branch = [];
        try {
            $stmt = $this->db->prepare("SELECT * FROM `branches` WHERE `id` = :bid LIMIT 1");
            $stmt->execute([':bid' => $branchId]);
            $branch = $stmt->fetch() ?: [];
        } catch (\Throwable $e) {}

        if (empty($branch)) {
            flash('error', 'Branch not found.');
            redirect(BASE_PATH . '/branch/dashboard');
        }

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

        // Common facility options
        $commonFacilities = [
            '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',
        ];

        $availableFacilities = array_column($facilities, 'facility_name');

        $this->branchAdminView('profile/index', [
            'title'              => 'Branch Profile',
            'currentPage'        => 'profile',
            'branch'             => $branch,
            'facilities'         => $facilities,
            'commonFacilities'   => $commonFacilities,
            'availableFacilities'=> $availableFacilities,
        ]);
    }

    /**
     * Update branch profile (only the fields branch admin is allowed to change).
     */
    public function update(): void
    {
        requireBranchAdmin();
        $this->validateCsrf();

        $branchId = $this->getBranchId();

        // Verify branch exists
        $stmt = $this->db->prepare("SELECT * FROM `branches` WHERE `id` = :bid LIMIT 1");
        $stmt->execute([':bid' => $branchId]);
        $branch = $stmt->fetch() ?: null;
        if (!$branch) {
            flash('error', 'Branch not found.');
            redirect(BASE_PATH . '/branch/dashboard');
        }

        // ─── Collect editable fields ───────────────────────────────────────
        $phone        = trim($_POST['phone'] ?? '') ?: null;
        $openingTime  = trim($_POST['opening_time'] ?? '') ?: null;
        $closingTime  = trim($_POST['closing_time'] ?? '') ?: null;
        $runningSince = trim($_POST['running_since'] ?? '') ?: null;
        $address      = trim($_POST['address'] ?? '');
        $pincode      = trim($_POST['pincode'] ?? '') ?: null;
        $mapLink      = trim($_POST['map_link'] ?? '') ?: null;
        $latitude     = ($_POST['latitude']  ?? '') !== '' ? (float) $_POST['latitude']  : null;
        $longitude    = ($_POST['longitude'] ?? '') !== '' ? (float) $_POST['longitude'] : null;
        $description  = $_POST['description'] ?? '';
        $gstNumber    = trim($_POST['gst_number'] ?? '') ?: null;
        $panNumber    = trim($_POST['pan_number'] ?? '') ?: null;

        // ─── Handle photo uploads (front, back, class, reception, logo/image) ──
        $photoFront = $branch['photo_front'] ?? null;
        $photoBack  = $branch['photo_back']  ?? null;
        $photoClass = $branch['photo_class'] ?? null;
        $photoRecep = $branch['photo_reception'] ?? null;
        $logoImage  = $branch['image'] ?? null;

        $uploaded = $this->handleImageUpload('photo_front', 'branches');
        if ($uploaded) { if ($photoFront) $this->deleteImageFile($photoFront); $photoFront = $uploaded; }
        $uploaded = $this->handleImageUpload('photo_back', 'branches');
        if ($uploaded) { if ($photoBack) $this->deleteImageFile($photoBack); $photoBack = $uploaded; }
        $uploaded = $this->handleImageUpload('photo_class', 'branches');
        if ($uploaded) { if ($photoClass) $this->deleteImageFile($photoClass); $photoClass = $uploaded; }
        $uploaded = $this->handleImageUpload('photo_reception', 'branches');
        if ($uploaded) { if ($photoRecep) $this->deleteImageFile($photoRecep); $photoRecep = $uploaded; }
        $uploaded = $this->handleImageUpload('image', 'branches');
        if ($uploaded) { if ($logoImage) $this->deleteImageFile($logoImage); $logoImage = $uploaded; }

        // ─── Update facilities ─────────────────────────────────────────────
        $submittedFacilities = $_POST['facilities'] ?? [];
        $customFacilities    = trim($_POST['custom_facilities'] ?? '');

        $facilitiesToInsert = [];
        if (is_array($submittedFacilities)) {
            foreach ($submittedFacilities as $facilityName => $value) {
                $facilitiesToInsert[] = trim(sanitize((string) $facilityName));
            }
        }
        if (!empty($customFacilities)) {
            foreach (explode(',', $customFacilities) as $customName) {
                $trimmed = trim(sanitize($customName));
                if (!empty($trimmed) && !in_array($trimmed, $facilitiesToInsert, true)) {
                    $facilitiesToInsert[] = $trimmed;
                }
            }
        }

        // ─── Transaction: update branch + sync facilities ──────────────────
        try {
            $this->db->beginTransaction();

            // Update branches table (only editable fields)
            $stmt = $this->db->prepare(
                "UPDATE `branches` SET
                    `phone` = :phone, `address` = :address, `pincode` = :pincode,
                    `opening_time` = :opening, `closing_time` = :closing,
                    `running_since` = :since, `map_link` = :map,
                    `latitude` = :lat, `longitude` = :lng,
                    `description` = :desc, `gst_number` = :gst, `pan_number` = :pan,
                    `photo_front` = :pf, `photo_back` = :pb, `photo_class` = :pc,
                    `photo_reception` = :pr, `image` = :logo,
                    `facilities` = :facilities_json,
                    `updated_at` = NOW()
                 WHERE `id` = :bid"
            );
            $stmt->execute([
                ':phone'    => $phone,
                ':address'  => $address,
                ':pincode'  => $pincode,
                ':opening'  => $openingTime,
                ':closing'  => $closingTime,
                ':since'    => $runningSince,
                ':map'      => $mapLink,
                ':lat'      => $latitude,
                ':lng'      => $longitude,
                ':desc'     => $description,
                ':gst'      => $gstNumber,
                ':pan'      => $panNumber,
                ':pf'       => $photoFront,
                ':pb'       => $photoBack,
                ':pc'       => $photoClass,
                ':pr'       => $photoRecep,
                ':logo'     => $logoImage,
                ':facilities_json' => json_encode($facilitiesToInsert),
                ':bid'      => $branchId,
            ]);

            // Sync branch_facilities table (delete + insert)
            try {
                $this->db->prepare("DELETE FROM `branch_facilities` WHERE `branch_id` = :bid")
                    ->execute([':bid' => $branchId]);

                if (!empty($facilitiesToInsert)) {
                    $stmt = $this->db->prepare(
                        "INSERT INTO `branch_facilities` (`branch_id`, `facility_name`, `is_available`, `description`)
                         VALUES (:bid, :fname, 1, NULL)"
                    );
                    foreach ($facilitiesToInsert as $f) {
                        $stmt->execute([':bid' => $branchId, ':fname' => $f]);
                    }
                }
            } catch (\Throwable $e) {
                // branch_facilities table might not exist — that's OK, we still have the JSON
            }

            $this->db->commit();

            $this->auditLog('branch_profile_update', 'branches', $branchId, 'Updated branch public profile');
            flash('success', 'Branch profile updated successfully.');
        } catch (\Throwable $e) {
            if ($this->db->inTransaction()) {
                $this->db->rollBack();
            }
            error_log('Branch profile update failed: ' . $e->getMessage());
            flash('error', 'Failed to update branch profile: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/branch/profile');
    }
}
