<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Affiliation Controller
 *
 * CRUD operations for affiliations and partners.
 */
class AdminAffiliationController extends AdminController
{
    /**
     * List all affiliations and partners.
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $type = $_GET['type'] ?? 'all';

        if ($type === 'affiliation' || $type === 'partner') {
            $stmt = $this->db->prepare(
                'SELECT * FROM `affiliations` WHERE `type` = :type ORDER BY `sort_order` ASC, `created_at` DESC'
            );
            $stmt->execute([':type' => $type]);
        } else {
            $stmt = $this->db->query(
                'SELECT * FROM `affiliations` ORDER BY `type` ASC, `sort_order` ASC, `created_at` DESC'
            );
        }

        $items = $stmt->fetchAll() ?: [];

        $this->adminView('affiliations', [
            'title'       => 'Manage Affiliations & Partners',
            'currentPage' => 'affiliations',
            'items'       => $items,
            'editItem'    => null,
            'currentType' => $type,
        ]);
    }

    /**
     * Store a new affiliation/partner.
     */
    public function store(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $name      = sanitize($_POST['name'] ?? '');
        $website   = sanitize($_POST['website'] ?? '');
        $type      = sanitize($_POST['type'] ?? 'affiliation');
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);
        $active    = isset($_POST['active']) ? 1 : 0;

        if (empty($name)) {
            flash('error', 'Organization name is required.');
            redirect(BASE_PATH . '/admin/affiliations');
        }

        $logoPath = $this->handleImageUpload('logo', 'affiliations');
        if ($logoPath === null) {
            $logoPath = '';
        }

        $stmt = $this->db->prepare(
            'INSERT INTO `affiliations` (`name`, `logo`, `website`, `type`, `sort_order`, `active`)
             VALUES (:name, :logo, :website, :type, :sort_order, :active)'
        );

        $stmt->execute([
            ':name'       => $name,
            ':logo'       => $logoPath,
            ':website'    => $website,
            ':type'       => $type,
            ':sort_order' => $sortOrder,
            ':active'     => $active,
        ]);

        flash('success', 'Affiliation/Partner added successfully.');
        redirect(BASE_PATH . '/admin/affiliations');
    }

    /**
     * Update an existing affiliation/partner.
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

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

        if ($item === null) {
            flash('error', 'Item not found.');
            redirect(BASE_PATH . '/admin/affiliations');
        }

        $name      = sanitize($_POST['name'] ?? '');
        $website   = sanitize($_POST['website'] ?? '');
        $type      = sanitize($_POST['type'] ?? 'affiliation');
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);
        $active    = isset($_POST['active']) ? 1 : 0;

        if (empty($name)) {
            flash('error', 'Organization name is required.');
            redirect(BASE_PATH . '/admin/affiliations');
        }

        $logoPath = $this->handleImageUpload('logo', 'affiliations');
        if ($logoPath !== null) {
            // New logo uploaded — delete the old one
            $this->deleteImageFile($item['logo'] ?? null);
        } else {
            $logoPath = $item['logo'];
        }

        $stmt = $this->db->prepare(
            'UPDATE `affiliations` SET `name` = :name, `logo` = :logo, `website` = :website,
             `type` = :type, `sort_order` = :sort_order, `active` = :active WHERE `id` = :id'
        );

        $stmt->execute([
            ':name'       => $name,
            ':logo'       => $logoPath,
            ':website'    => $website,
            ':type'       => $type,
            ':sort_order' => $sortOrder,
            ':active'     => $active,
            ':id'         => $id,
        ]);

        flash('success', 'Affiliation/Partner updated successfully.');
        redirect(BASE_PATH . '/admin/affiliations');
    }

    /**
     * Delete an affiliation/partner.
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

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

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

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

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