<?php

namespace Admin\Controllers;

use Admin\Controllers\AdminController;

class AdminAnnouncementController extends AdminController
{
    /**
     * List all announcements
     */
    public function index()
    {
        requireAdmin();

        $stmt = $this->db->prepare("
            SELECT a.*, b.name AS branch_name
            FROM announcements a
            LEFT JOIN branches b ON a.branch_id = b.id
            ORDER BY a.created_at DESC
        ");
        $stmt->execute();
        $announcements = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        return $this->adminView('announcements/index', [
            'announcements' => $announcements
        ]);
    }

    /**
     * Show create form with branches dropdown
     */
    public function create()
    {
        requireAdmin();

        $stmt = $this->db->prepare("SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name ASC");
        $stmt->execute();
        $branches = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        return $this->adminView('announcements/create', [
            'branches' => $branches
        ]);
    }

    /**
     * Insert a new announcement
     */
    public function store()
    {
        requireAdmin();

        $this->validateCsrf();

        $title    = sanitize($_POST['title'] ?? '');
        $content  = sanitize($_POST['content'] ?? '');
        $type     = sanitize($_POST['type'] ?? 'general');
        $branchId = !empty($_POST['branch_id']) ? (int) $_POST['branch_id'] : null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if ($title === '') {
            flash('error', 'Title is required.');
            redirect(BASE_PATH . '/admin/announcements/create');
            return;
        }

        // Validate type enum
        $validTypes = ['general', 'exam', 'admission', 'event'];
        if (!in_array($type, $validTypes)) {
            $type = 'general';
        }

        // Handle image upload
        $image = null;
        if (!empty($_FILES['image']['name'])) {
            $image = $this->handleImageUpload('image', 'announcements');
        }

        try {
            $stmt = $this->db->prepare("
                INSERT INTO announcements (title, content, type, branch_id, is_active, image, created_at, updated_at)
                VALUES (:title, :content, :type, :branch_id, :is_active, :image, NOW(), NOW())
            ");
            $stmt->execute([
                'title'     => $title,
                'content'   => $content,
                'type'      => $type,
                'branch_id' => $branchId,
                'is_active' => $isActive,
                'image'     => $image
            ]);

            flash('success', 'Announcement created successfully.');
        } catch (\Exception $e) {
            flash('error', 'Failed to create announcement: ' . $e->getMessage());
        }

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

    /**
     * Show edit form
     */
    public function edit($params)
    {
        requireAdmin();

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

        $stmt = $this->db->prepare("SELECT * FROM announcements WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $announcement = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        $stmt = $this->db->prepare("SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name ASC");
        $stmt->execute();
        $branches = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        return $this->adminView('announcements/edit', [
            'announcement' => $announcement,
            'branches'     => $branches
        ]);
    }

    /**
     * Update an announcement
     */
    public function update($params)
    {
        requireAdmin();

        $this->validateCsrf();

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

        $stmt = $this->db->prepare("SELECT * FROM announcements WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $announcement = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        $title    = sanitize($_POST['title'] ?? '');
        $content  = sanitize($_POST['content'] ?? '');
        $type     = sanitize($_POST['type'] ?? 'general');
        $branchId = !empty($_POST['branch_id']) ? (int) $_POST['branch_id'] : null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if ($title === '') {
            flash('error', 'Title is required.');
            redirect(BASE_PATH . '/admin/announcements/edit/' . $id);
            return;
        }

        // Validate type enum
        $validTypes = ['general', 'exam', 'admission', 'event'];
        if (!in_array($type, $validTypes)) {
            $type = 'general';
        }

        // Handle image upload
        $image = $announcement['image'];
        if (!empty($_FILES['image']['name'])) {
            // Delete old image if exists
            if ($image) {
                $this->deleteImageFile($image);
            }
            $image = $this->handleImageUpload('image', 'announcements');
        } elseif (isset($_POST['remove_image']) && $_POST['remove_image'] == '1') {
            // Remove existing image
            if ($image) {
                $this->deleteImageFile($image);
            }
            $image = null;
        }

        try {
            $stmt = $this->db->prepare("
                UPDATE announcements
                SET title = :title, content = :content, type = :type,
                    branch_id = :branch_id, is_active = :is_active, image = :image, updated_at = NOW()
                WHERE id = :id
            ");
            $stmt->execute([
                'title'     => $title,
                'content'   => $content,
                'type'      => $type,
                'branch_id' => $branchId,
                'is_active' => $isActive,
                'image'     => $image,
                'id'        => $id
            ]);

            flash('success', 'Announcement updated successfully.');
        } catch (\Exception $e) {
            flash('error', 'Failed to update announcement: ' . $e->getMessage());
        }

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

    /**
     * Delete an announcement
     */
    public function delete($params)
    {
        requireAdmin();

        $this->validateCsrf();

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

        $stmt = $this->db->prepare("SELECT * FROM announcements WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $announcement = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        // Delete associated image
        if ($announcement['image']) {
            $this->deleteImageFile($announcement['image']);
        }

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

        flash('success', 'Announcement deleted successfully.');
        redirect(BASE_PATH . '/admin/announcements');
    }

    /**
     * Toggle is_active status
     */
    public function toggleStatus($params)
    {
        requireAdmin();

        $this->validateCsrf();

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

        $stmt = $this->db->prepare("SELECT id, is_active FROM announcements WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $announcement = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        $newStatus = $announcement['is_active'] ? 0 : 1;

        $stmt = $this->db->prepare("
            UPDATE announcements SET is_active = :is_active, updated_at = NOW() WHERE id = :id
        ");
        $stmt->execute([
            'is_active' => $newStatus,
            'id'        => $id
        ]);

        $statusText = $newStatus ? 'activated' : 'deactivated';
        flash('success', 'Announcement ' . $statusText . ' successfully.');
        redirect(BASE_PATH . '/admin/announcements');
    }
}
