<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Branch Controller
 *
 * CRUD operations for institute branch locations.
 */
class AdminBranchController extends AdminController
{
    /**
     * List all branches.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query('SELECT * FROM `branches` ORDER BY `created_at` DESC');
        $branches = $stmt->fetchAll() ?: [];

        $this->adminView('branches', [
            'title'       => 'Manage Branches',
            'currentPage' => 'branches',
            'branches'    => $branches,
            'editBranch'  => null,
        ]);
    }

    /**
     * Show the create branch form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function create(array $params = []): void
    {
        requireAdmin();

        $this->adminView('branches', [
            'title'       => 'Add New Branch',
            'currentPage' => 'branches',
            'branches'    => [],
            'editBranch'  => null,
            'showForm'    => true,
        ]);
    }

    /**
     * Store a new branch.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function store(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $name     = sanitize($_POST['name'] ?? '');
        $city     = sanitize($_POST['city'] ?? '');
        $state    = sanitize($_POST['state'] ?? '');
        $address  = sanitize($_POST['address'] ?? '');
        $phone    = sanitize($_POST['phone'] ?? '');
        $mapLink  = sanitize($_POST['map_link'] ?? '');
        // Default active=1 so branches show on website immediately
        $active   = isset($_POST['active']) ? 1 : 1;

        if (empty($name) || empty($city) || empty($state)) {
            flash('error', 'Branch name, city, and state are required.');
            redirect(BASE_PATH . '/admin/branches/create');
        }

        // Provide default for address if empty (database has NOT NULL constraint)
        if (empty($address)) {
            $address = $city . ', ' . $state;
        }

        // Handle optional image upload
        $imagePath = $this->handleImageUpload('image', 'branches');

        try {
            $stmt = $this->db->prepare(
                'INSERT INTO `branches` (`name`, `city`, `state`, `address`, `phone`, `map_link`, `image`, `active`)
                 VALUES (:name, :city, :state, :address, :phone, :map_link, :image, :active)'
            );

            $stmt->execute([
                ':name'     => $name,
                ':city'     => $city,
                ':state'    => $state,
                ':address'  => $address,
                ':phone'    => $phone,
                ':map_link' => $mapLink,
                ':image'    => $imagePath,
                ':active'   => $active,
            ]);

            flash('success', 'Branch created successfully.');
        } catch (\Throwable $e) {
            error_log('Branch create error: ' . $e->getMessage());
            // Delete uploaded image if DB insert failed
            if ($imagePath !== null) {
                $this->deleteImageFile($imagePath);
            }
            flash('error', 'Failed to create branch. Please try again.');
        }

        redirect(BASE_PATH . '/admin/branches');
    }

    /**
     * Show the edit branch form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function edit(array $params = []): void
    {
        requireAdmin();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('SELECT * FROM `branches` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $editBranch = $stmt->fetch() ?: null;

        if ($editBranch === null) {
            flash('error', 'Branch not found.');
            redirect(BASE_PATH . '/admin/branches');
        }

        $this->adminView('branches', [
            'title'       => 'Edit Branch',
            'currentPage' => 'branches',
            'branches'    => [],
            'editBranch'  => $editBranch,
            'showForm'    => true,
        ]);
    }

    /**
     * Update an existing branch.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('SELECT * FROM `branches` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $branch = $stmt->fetch() ?: null;

        if ($branch === null) {
            flash('error', 'Branch not found.');
            redirect(BASE_PATH . '/admin/branches');
        }

        $name     = sanitize($_POST['name'] ?? '');
        $city     = sanitize($_POST['city'] ?? '');
        $state    = sanitize($_POST['state'] ?? '');
        $address  = sanitize($_POST['address'] ?? '');
        $phone    = sanitize($_POST['phone'] ?? '');
        $mapLink  = sanitize($_POST['map_link'] ?? '');
        // Default active=1 so branches show on website immediately
        $active   = isset($_POST['active']) ? 1 : 1;

        if (empty($name) || empty($city) || empty($state)) {
            flash('error', 'Branch name, city, and state are required.');
            redirect(BASE_PATH . '/admin/branches/' . $id . '/edit');
        }

        // Handle optional image replacement
        $imagePath = $this->handleImageUpload('image', 'branches');
        if ($imagePath !== null) {
            // New image uploaded — delete the old one
            $this->deleteImageFile($branch['image'] ?? null);
        } else {
            $imagePath = $branch['image'];
        }

        $stmt = $this->db->prepare(
            'UPDATE `branches` SET `name` = :name, `city` = :city, `state` = :state,
             `address` = :address, `phone` = :phone, `map_link` = :map_link,
             `image` = :image, `active` = :active WHERE `id` = :id'
        );

        $stmt->execute([
            ':name'     => $name,
            ':city'     => $city,
            ':state'    => $state,
            ':address'  => $address,
            ':phone'    => $phone,
            ':map_link' => $mapLink,
            ':image'    => $imagePath,
            ':active'   => $active,
            ':id'       => $id,
        ]);

        flash('success', 'Branch updated successfully.');
        redirect(BASE_PATH . '/admin/branches');
    }

    /**
     * Delete a branch.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        // Fetch the branch first to delete its image file
        $stmt = $this->db->prepare('SELECT * FROM `branches` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $branch = $stmt->fetch() ?: null;

        if ($branch !== null) {
            $this->deleteImageFile($branch['image'] ?? null);
        }

        $stmt = $this->db->prepare('DELETE FROM `branches` WHERE `id` = :id');
        $stmt->execute([':id' => $id]);

        if ($stmt->rowCount() > 0) {
            flash('success', 'Branch deleted successfully.');
        } else {
            flash('warning', 'Branch not found or already deleted.');
        }
        redirect(BASE_PATH . '/admin/branches');
    }
}
