<?php

declare(strict_types=1);

namespace SuperAdmin\Controllers;

/**
 * Super Admin Announcement Controller
 *
 * CRUD for announcements. Super Admin can create:
 *   - Global announcements (branch_id=NULL → visible in ALL branch dashboards)
 *   - Branch-specific announcements (branch_id=X → visible only in that branch)
 *
 * Announcements support: title, text (short), content (full), type (general/urgent/info),
 * priority, link, image, is_active, start/end dates.
 */
class SuperAdminAnnouncementController extends SuperAdminBaseController
{
    /**
     * List all announcements.
     */
    public function index(): void
    {
        requireSuperAdmin();

        $scopeFilter = trim($_GET['scope'] ?? '');

        $sql = "SELECT a.*, b.`name` AS branch_name, b.`branch_code`
                FROM `announcements` a
                LEFT JOIN `branches` b ON a.`branch_id` = b.`id`
                WHERE 1=1";
        $params = [];

        if ($scopeFilter === 'global') {
            $sql .= " AND a.`branch_id` IS NULL";
        } elseif ($scopeFilter === 'branch') {
            $sql .= " AND a.`branch_id` IS NOT NULL";
        }
        $sql .= " ORDER BY a.`created_at` DESC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $announcements = $stmt->fetchAll() ?: [];

        $this->superAdminView('announcements/index', [
            'title'       => 'Announcements',
            'currentPage' => 'announcements',
            'announcements' => $announcements,
            'scopeFilter' => $scopeFilter,
        ]);
    }

    /**
     * Show create form.
     */
    public function create(): void
    {
        requireSuperAdmin();

        $branches = [];
        try {
            $stmt = $this->db->query("SELECT `id`, `name`, `branch_code` FROM `branches` WHERE `status` = 'active' ORDER BY `branch_code` ASC");
            $branches = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        $this->superAdminView('announcements/create', [
            'title'       => 'Create Announcement',
            'currentPage' => 'announcements',
            'branches'    => $branches,
        ]);
    }

    /**
     * Store a new announcement.
     */
    public function store(): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

        $title    = trim($_POST['title'] ?? '');
        $text     = trim($_POST['text'] ?? '');
        $content  = $_POST['content'] ?? '';
        $textHi   = trim($_POST['text_hi'] ?? '') ?: null;
        $type     = trim($_POST['type'] ?? 'general');
        $branchId = (int) ($_POST['branch_id'] ?? 0) ?: null; // NULL = global
        $link     = trim($_POST['link'] ?? '') ?: null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if (empty($title) || empty($text)) {
            flash('error', 'Title and short text are required.');
            redirect(BASE_PATH . '/super-admin/announcements/create');
        }

        if (!in_array($type, ['general','urgent','info'], true)) $type = 'general';

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

        try {
            $stmt = $this->db->prepare(
                "INSERT INTO `announcements`
                    (`title`, `text`, `text_hi`, `content`, `type`, `branch_id`,
                     `link`, `image`, `active`, `is_active`, `created_at`, `updated_at`)
                 VALUES
                    (:title, :text, :text_hi, :content, :type, :branch_id,
                     :link, :image, :active, :is_active, NOW(), NOW())"
            );
            $stmt->execute([
                ':title'     => $title,
                ':text'      => $text,
                ':text_hi'   => $textHi,
                ':content'   => $content ?: null,
                ':type'      => $type,
                ':branch_id' => $branchId,
                ':link'      => $link,
                ':image'     => $imagePath,
                ':active'    => $isActive,
                ':is_active' => $isActive,
            ]);
            $annId = (int) $this->db->lastInsertId();

            $scope = $branchId ? "branch #{$branchId}" : 'global';
            $this->auditLog('announcement_create', 'announcements', $annId, "Created {$type} announcement '{$title}' ({$scope})");
            flash('success', "Announcement '{$title}' created successfully (" . ($branchId ? 'branch-specific' : 'global') . ").");
        } catch (\Throwable $e) {
            flash('error', 'Failed to create announcement: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/super-admin/announcements');
    }

    /**
     * Show edit form.
     */
    public function edit(int $id): void
    {
        requireSuperAdmin();

        $stmt = $this->db->prepare(
            "SELECT a.*, b.`name` AS branch_name, b.`branch_code`
             FROM `announcements` a
             LEFT JOIN `branches` b ON a.`branch_id` = b.`id`
             WHERE a.`id` = :id LIMIT 1"
        );
        $stmt->execute([':id' => $id]);
        $announcement = $stmt->fetch() ?: null;

        if (!$announcement) {
            flash('error', 'Announcement not found.');
            redirect(BASE_PATH . '/super-admin/announcements');
        }

        $branches = [];
        try {
            $stmt = $this->db->query("SELECT `id`, `name`, `branch_code` FROM `branches` WHERE `status` = 'active' ORDER BY `branch_code` ASC");
            $branches = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        $this->superAdminView('announcements/edit', [
            'title'        => 'Edit Announcement',
            'currentPage'  => 'announcements',
            'announcement' => $announcement,
            'branches'     => $branches,
        ]);
    }

    /**
     * Update an announcement.
     */
    public function update(int $id): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

        $stmt = $this->db->prepare("SELECT * FROM `announcements` WHERE `id` = :id LIMIT 1");
        $stmt->execute([':id' => $id]);
        $announcement = $stmt->fetch() ?: null;
        if (!$announcement) {
            flash('error', 'Announcement not found.');
            redirect(BASE_PATH . '/super-admin/announcements');
        }

        $title    = trim($_POST['title'] ?? '');
        $text     = trim($_POST['text'] ?? '');
        $content  = $_POST['content'] ?? '';
        $textHi   = trim($_POST['text_hi'] ?? '') ?: null;
        $type     = trim($_POST['type'] ?? 'general');
        $branchId = (int) ($_POST['branch_id'] ?? 0) ?: null;
        $link     = trim($_POST['link'] ?? '') ?: null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if (empty($title) || empty($text)) {
            flash('error', 'Title and short text are required.');
            redirect(BASE_PATH . '/super-admin/announcements/' . $id . '/edit');
        }

        if (!in_array($type, ['general','urgent','info'], true)) $type = 'general';

        $imagePath = $announcement['image'];
        $uploaded = $this->handleImageUpload('image', 'announcements');
        if ($uploaded) {
            if ($imagePath) $this->deleteImageFile($imagePath);
            $imagePath = $uploaded;
        }

        try {
            $stmt = $this->db->prepare(
                "UPDATE `announcements` SET
                    `title` = :title, `text` = :text, `text_hi` = :text_hi,
                    `content` = :content, `type` = :type, `branch_id` = :branch_id,
                    `link` = :link, `image` = :image,
                    `active` = :active, `is_active` = :is_active, `updated_at` = NOW()
                 WHERE `id` = :id"
            );
            $stmt->execute([
                ':title'     => $title,
                ':text'      => $text,
                ':text_hi'   => $textHi,
                ':content'   => $content ?: null,
                ':type'      => $type,
                ':branch_id' => $branchId,
                ':link'      => $link,
                ':image'     => $imagePath,
                ':active'    => $isActive,
                ':is_active' => $isActive,
                ':id'        => $id,
            ]);

            $this->auditLog('announcement_update', 'announcements', $id, "Updated announcement '{$title}'");
            flash('success', 'Announcement updated successfully.');
        } catch (\Throwable $e) {
            flash('error', 'Failed to update announcement: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/super-admin/announcements');
    }

    /**
     * Delete an announcement.
     */
    public function delete(int $id): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

        try {
            $stmt = $this->db->prepare("SELECT `image` FROM `announcements` WHERE `id` = :id LIMIT 1");
            $stmt->execute([':id' => $id]);
            $ann = $stmt->fetch() ?: null;
            if ($ann && !empty($ann['image'])) {
                $this->deleteImageFile($ann['image']);
            }
            $this->db->prepare("DELETE FROM `announcements` WHERE `id` = :id")->execute([':id' => $id]);
            $this->auditLog('announcement_delete', 'announcements', $id, 'Deleted announcement');
            flash('success', 'Announcement deleted.');
        } catch (\Throwable $e) {
            flash('error', 'Failed to delete: ' . $e->getMessage());
        }
        redirect(BASE_PATH . '/super-admin/announcements');
    }
}
