<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Helpers\Url;
use App\Helpers\Mailer;
use App\Models\Announcement;
use App\Models\AuditLog;
use App\Models\PostCategory;
use App\Models\User;

class AnnouncementController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $model = new Announcement();
        $categoryModel = new PostCategory();
        $categories = $categoryModel->getActive();

        if (Auth::check()) {
            $filterType = $_GET['type'] ?? '';
            if ($filterType) {
                $announcements = $model->getByType($filterType);
            } else {
                $announcements = $model->getAllWithCategory();
            }
            $this->view('announcements/index', [
                'announcements' => $announcements,
                'categories' => $categories,
                'filterType' => $filterType,
            ]);
        } else {
            $announcements = $model->getPublic(20);
            $this->view('announcements/public', ['announcements' => $announcements], false);
        }
    }

    public function create()
    {
        Auth::requireLogin();
        $categoryModel = new PostCategory();
        $categories = $categoryModel->getActive();
        $this->view('announcements/form', ['categories' => $categories]);
    }

    public function store()
    {
        Auth::requireLogin();
        $model = new Announcement();
        $imagePath = $this->handleImageUpload('image');

        $data = [
            'title' => $_POST['title'] ?? '',
            'post_type' => $_POST['post_type'] ?? 'announcement',
            'content' => $_POST['content'] ?? '',
            'excerpt' => $_POST['excerpt'] ?? '',
            'image' => $imagePath,
            'link_url' => $_POST['link_url'] ?? null,
            'category_id' => !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null,
            'priority' => $_POST['priority'] ?? 'normal',
            'visibility' => $_POST['visibility'] ?? 'public',
            'status' => $_POST['status'] ?? 'draft',
            'created_by' => Auth::id(),
        ];

        if ($data['status'] === 'published') {
            $data['published_at'] = date('Y-m-d H:i:s');
        }

        $model->create($data);

        if ($data['status'] === 'published') {
            $userModel = new User();
            $members = $userModel->where('approval_status', 'approved');
            foreach ($members as $member) {
                if ($member->email) {
                    Mailer::sendAnnouncement($member->email, $member->first_name ?: $member->name, $data['title'], $data['content']);
                }
            }
        }

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'announcement.create', 'announcements', $model->db->lastInsertId(), "Created announcement: {$data['title']}");

        $_SESSION['success'] = 'Announcement created successfully';
        $this->redirect('/announcements');
    }

    public function edit($params)
    {
        Auth::requireLogin();
        $model = new Announcement();
        $announcement = $model->getWithAuthor($params['id'] ?? null);
        if (!$announcement) {
            $_SESSION['error'] = 'Announcement not found';
            $this->redirect('/announcements');
        }
        $categoryModel = new PostCategory();
        $categories = $categoryModel->getActive();
        $this->view('announcements/form', ['announcement' => $announcement, 'categories' => $categories]);
    }

    public function update($params)
    {
        Auth::requireLogin();
        $id = $params['id'] ?? null;
        $model = new Announcement();
        $announcement = $model->find($id);
        if (!$announcement) {
            $_SESSION['error'] = 'Announcement not found';
            $this->redirect('/announcements');
        }

        $imagePath = $announcement->image;
        if (!empty($_FILES['image']['name'])) {
            if ($imagePath && file_exists($imagePath)) {
                unlink($imagePath);
            }
            $imagePath = $this->handleImageUpload('image');
        }

        $data = [
            'title' => $_POST['title'] ?? '',
            'post_type' => $_POST['post_type'] ?? 'announcement',
            'content' => $_POST['content'] ?? '',
            'excerpt' => $_POST['excerpt'] ?? '',
            'image' => $imagePath,
            'link_url' => $_POST['link_url'] ?? null,
            'category_id' => !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null,
            'priority' => $_POST['priority'] ?? 'normal',
            'visibility' => $_POST['visibility'] ?? 'public',
            'status' => $_POST['status'] ?? 'draft',
        ];

        if ($data['status'] === 'published' && !$announcement->published_at) {
            $data['published_at'] = date('Y-m-d H:i:s');
        }

        $model->update($id, $data);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'announcement.update', 'announcements', $id, "Updated announcement: {$data['title']}");

        $_SESSION['success'] = 'Announcement updated successfully';
        $this->redirect('/announcements');
    }

    public function delete($params)
    {
        Auth::requireLogin();
        $id = $params['id'] ?? null;
        $model = new Announcement();
        $announcement = $model->find($id);
        if ($announcement) {
            if ($announcement->image && file_exists($announcement->image)) {
                unlink($announcement->image);
            }
            $audit = new AuditLog();
            $audit->log(Auth::id(), 'announcement.delete', 'announcements', $id, "Deleted announcement: {$announcement->title}");
            $model->delete($id);
            $_SESSION['success'] = 'Announcement deleted';
        }
        $this->redirect('/announcements');
    }

    private function handleImageUpload($fieldName)
    {
        if (empty($_FILES[$fieldName]['name'])) {
            return null;
        }
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $ext = strtolower(pathinfo($_FILES[$fieldName]['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) {
            return null;
        }
        $uploadDir = $_SERVER['DOCUMENT_ROOT'] . Url::getBaseUrl() . '/uploads/announcements/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        $filename = uniqid('ann_') . '.' . $ext;
        $dest = $uploadDir . $filename;
        if (move_uploaded_file($_FILES[$fieldName]['tmp_name'], $dest)) {
            return 'uploads/announcements/' . $filename;
        }
        return null;
    }
}
