<?php

namespace Modules\Marketing\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Security;

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

    public function index(): void
    {
        $this->requirePermission('marketing_dashboard');

        $db = Database::getInstance();
        $totalCampaigns = $db->table('campaigns')->count();
        $activeCampaigns = $db->table('campaigns')->where('status', 'active')->count();
        $emailTemplates = $db->table('email_templates')->count();
        $smsTemplates = $db->table('sms_templates')->count();

        $this->view('Marketing/campaigns', [
            'title' => 'Marketing Dashboard',
            'breadcrumb' => ['Marketing' => url('marketing')],
            'totalCampaigns' => $totalCampaigns,
            'activeCampaigns' => $activeCampaigns,
            'emailTemplates' => $emailTemplates,
            'smsTemplates' => $smsTemplates,
        ]);
    }

    public function campaigns(): void
    {
        $this->requirePermission('marketing_campaigns_view');

        $db = Database::getInstance();
        $status = $this->request->get('status', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('campaigns');

        if (!empty($status)) {
            $query->where('status', $status);
        }

        $campaigns = $query->orderBy('created_at', 'DESC')->paginate($perPage, $page);

        $this->view('Marketing/campaigns', [
            'title' => 'Campaigns',
            'breadcrumb' => ['Campaigns' => url('marketing/campaigns')],
            'campaigns' => $campaigns,
            'status' => $status,
        ]);
    }

    public function storeCampaign(): void
    {
        $this->requirePermission('marketing_campaigns_create');

        $validated = $this->validate([
            'name' => 'required|max_length:255',
            'type' => 'required|in:email,sms,both',
            'subject' => 'required_if:type,email,both|max_length:255',
            'message' => 'required|max_length:5000',
            'audience' => 'required|in:all,customers,leads',
            'scheduled_at' => 'date',
        ]);

        $validated['status'] = 'draft';
        $validated['created_by'] = Auth::id();

        if (!empty($validated['scheduled_at'])) {
            $validated['status'] = 'scheduled';
        }

        $campaignId = Database::getInstance()->table('campaigns')->insert($validated);
        $this->logActivity('create', 'Created campaign: ' . $validated['name']);
        $this->logAudit('create', 'campaigns', $campaignId, null, $validated);

        $this->redirectWith(url('marketing/campaigns'), 'success', 'Campaign created successfully.');
    }

    public function emailTemplates(): void
    {
        $this->requirePermission('marketing_templates_view');

        $db = Database::getInstance();
        $templates = $db->table('email_templates')
            ->orderBy('name', 'ASC')
            ->get();

        $this->view('Marketing/email_templates', [
            'title' => 'Email Templates',
            'breadcrumb' => ['Email Templates' => url('marketing/email-templates')],
            'templates' => $templates,
        ]);
    }

    public function storeEmailTemplate(): void
    {
        $this->requirePermission('marketing_templates_manage');

        $validated = $this->validate([
            'name' => 'required|max_length:100',
            'subject' => 'required|max_length:255',
            'body' => 'required',
            'variables' => 'max_length:1000',
            'is_active' => 'in:0,1',
        ]);

        $validated['is_active'] = $validated['is_active'] ?? 1;
        $id = $this->request->post('id');

        if (!empty($id)) {
            $existing = Database::getInstance()->table('email_templates')->find($id);
            if (!$existing) {
                $this->redirectWith(url('marketing/email-templates'), 'error', 'Template not found.');
            }
            $oldValues = (array)$existing;
            Database::getInstance()->table('email_templates')->where('id', $id)->update($validated);
            $this->logAudit('update', 'email_templates', $id, $oldValues, $validated);
            $msg = 'Email template updated successfully.';
        } else {
            $id = Database::getInstance()->table('email_templates')->insert($validated);
            $this->logAudit('create', 'email_templates', $id, null, $validated);
            $msg = 'Email template created successfully.';
        }

        $this->logActivity('manage_template', $msg . ': ' . $validated['name']);
        $this->redirectWith(url('marketing/email-templates'), 'success', $msg);
    }

    public function smsTemplates(): void
    {
        $this->requirePermission('marketing_templates_view');

        $db = Database::getInstance();
        $templates = $db->table('sms_templates')
            ->orderBy('name', 'ASC')
            ->get();

        $this->view('Marketing/sms_templates', [
            'title' => 'SMS Templates',
            'breadcrumb' => ['SMS Templates' => url('marketing/sms-templates')],
            'templates' => $templates,
        ]);
    }

    public function storeSmsTemplate(): void
    {
        $this->requirePermission('marketing_templates_manage');

        $validated = $this->validate([
            'name' => 'required|max_length:100',
            'message' => 'required|max_length:1600',
            'variables' => 'max_length:1000',
            'is_active' => 'in:0,1',
        ]);

        $validated['is_active'] = $validated['is_active'] ?? 1;
        $id = $this->request->post('id');

        if (!empty($id)) {
            $existing = Database::getInstance()->table('sms_templates')->find($id);
            if (!$existing) {
                $this->redirectWith(url('marketing/sms-templates'), 'error', 'Template not found.');
            }
            $oldValues = (array)$existing;
            Database::getInstance()->table('sms_templates')->where('id', $id)->update($validated);
            $this->logAudit('update', 'sms_templates', $id, $oldValues, $validated);
            $msg = 'SMS template updated successfully.';
        } else {
            $id = Database::getInstance()->table('sms_templates')->insert($validated);
            $this->logAudit('create', 'sms_templates', $id, null, $validated);
            $msg = 'SMS template created successfully.';
        }

        $this->logActivity('manage_template', $msg . ': ' . $validated['name']);
        $this->redirectWith(url('marketing/sms-templates'), 'success', $msg);
    }
}
