<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\AutomationRule;
use App\Models\PipelineStage;
use App\Models\Tag;
use App\Models\User;
use App\Models\Setting;

class AutomationController extends Controller {
    public function index(): void {
        $rules = AutomationRule::all('id ASC');
        $stages = PipelineStage::getOrdered();
        $tags = Tag::all('name ASC');
        $agents = User::getActiveAgents();

        $workingHours = [
            'enabled' => Setting::getVal('working_hours_enabled', '0'),
            'start'   => Setting::getVal('working_hours_start', '09:00'),
            'end'     => Setting::getVal('working_hours_end', '18:00'),
            'reply'   => Setting::getVal('out_of_office_reply', 'Our team is currently away. We will respond during business hours.')
        ];

        $this->render('automations/index', [
            'rules'        => $rules,
            'stages'       => $stages,
            'tags'         => $tags,
            'agents'       => $agents,
            'workingHours' => $workingHours
        ]);
    }

    public function store(): void {
        $name = trim(Request::post('name', ''));
        $triggerEvent = Request::post('trigger_event');
        $triggerKeyword = trim(Request::post('trigger_keyword', ''));
        $replyType = Request::post('reply_type', 'text');
        $replyContent = trim(Request::post('reply_content', ''));
        $actionType = Request::post('action_type', 'none');
        $actionValue = Request::post('action_value');

        if (empty($name) || empty($replyContent)) {
            Response::error('Rule name and automated reply content are required.');
        }

        $id = AutomationRule::create([
            'name'            => $name,
            'trigger_event'   => $triggerEvent,
            'trigger_keyword' => $triggerKeyword ?: null,
            'reply_type'      => $replyType,
            'reply_content'   => $replyContent,
            'action_type'     => $actionType,
            'action_value'    => $actionValue ?: null,
            'is_active'       => 1,
            'created_at'      => date('Y-m-d H:i:s')
        ]);

        if (Request::isAjax()) {
            Response::success(AutomationRule::find($id), 'Automation rule created');
        }
        Response::redirect('/automations');
    }

    public function toggle(int $id): void {
        $rule = AutomationRule::find($id);
        if ($rule) {
            $newStatus = $rule['is_active'] ? 0 : 1;
            AutomationRule::update($id, ['is_active' => $newStatus]);
            Response::success(['is_active' => $newStatus], 'Rule status updated');
        }
        Response::error('Rule not found', 404);
    }

    public function delete(int $id): void {
        AutomationRule::delete($id);
        if (Request::isAjax()) {
            Response::success(null, 'Rule deleted');
        }
        Response::redirect('/automations');
    }

    public function saveWorkingHours(): void {
        $enabled = Request::post('working_hours_enabled') ? '1' : '0';
        $start = Request::post('working_hours_start', '09:00');
        $end = Request::post('working_hours_end', '18:00');
        $reply = trim(Request::post('out_of_office_reply', ''));

        Setting::setVal('working_hours_enabled', $enabled, 'automation');
        Setting::setVal('working_hours_start', $start, 'automation');
        Setting::setVal('working_hours_end', $end, 'automation');
        Setting::setVal('out_of_office_reply', $reply, 'automation');

        if (Request::isAjax()) {
            Response::success(null, 'Working hours configuration saved');
        }
        Response::redirect('/automations');
    }
}
