<?php

namespace Modules\Reports\Controllers;

use Modules\Reports\Models\ReportTemplateModel;
use Core\Controller;
use Core\Auth;

class ReportTemplateController extends Controller
{
    private ReportTemplateModel $templateModel;

    public function __construct()
    {
        parent::__construct();
        $this->templateModel = new ReportTemplateModel();
    }

    public function index()
    {
        $this->requireAuth();
        $orgId = $this->scopedOrgId();
        $templates = $this->templateModel->getAllForOrg($orgId);
        $this->render('reports/templates/index', ['templates' => $templates, 'isPlatformView' => $orgId === null]);
    }

    public function create()
    {
        $this->requireAuth();
        $this->render('reports/templates/form', [
            'template' => null,
            'sections' => [],
            'workloadItems' => [],
        ]);
    }

    public function store()
    {
        $this->requireAuth();
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token. Please try again.');
            $this->redirect('/reports/templates/create');
        }

        if (Auth::orgId() === null) {
            $this->setFlash('error', 'Report templates belong to an organization. Log in as an organization user to create one.');
            $this->redirect('/reports/templates');
        }

        $templateData = [
            'org_id' => Auth::orgId(),
            'name' => trim($_POST['name'] ?? ''),
            'description' => $_POST['description'] ?? '',
            'created_by' => Auth::id(),
        ];

        if (empty($templateData['name'])) {
            $this->setFlash('error', 'Template name is required.');
            $this->redirect('/reports/templates/create');
        }

        $sections = $_POST['sections'] ?? [];
        $workloadItems = $_POST['workload_items'] ?? [];

        $templateId = $this->templateModel->createTemplate($templateData, $sections, $workloadItems);

        logAudit('report_template_created', 'reports', 'report_template', $templateId);
        $this->setFlash('success', 'Template created successfully.');
        $this->redirect('/reports/templates');
    }

    public function edit($id)
    {
        $this->requireAuth();
        $templateData = $this->templateModel->getWithSections((int)$id);
        if (!$templateData || (!Auth::isSuperAdmin() && (int)$templateData['template']['org_id'] !== (int)Auth::orgId())) {
            $this->setFlash('error', 'Template not found.');
            $this->redirect('/reports/templates');
        }

        $this->render('reports/templates/form', [
            'template' => $templateData['template'],
            'sections' => $templateData['sections'],
            'workloadItems' => $templateData['workload_items'],
        ]);
    }

    public function update($id)
    {
        $this->requireAuth();
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token. Please try again.');
            $this->redirect('/reports/templates/' . $id . '/edit');
        }

        $existing = $this->templateModel->find((int)$id);
        if (!$existing || (!Auth::isSuperAdmin() && (int)$existing['org_id'] !== (int)Auth::orgId())) {
            $this->setFlash('error', 'Template not found.');
            $this->redirect('/reports/templates');
        }

        $templateData = [
            'name' => trim($_POST['name'] ?? ''),
            'description' => $_POST['description'] ?? '',
        ];

        $sections = $_POST['sections'] ?? [];
        $workloadItems = $_POST['workload_items'] ?? [];

        $this->templateModel->updateTemplate((int)$id, $templateData, $sections, $workloadItems);

        logAudit('report_template_updated', 'reports', 'report_template', (int)$id);
        $this->setFlash('success', 'Template updated successfully.');
        $this->redirect('/reports/templates');
    }

    public function delete($id)
    {
        $this->requireAuth();
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token. Please try again.');
            $this->redirect('/reports/templates');
        }

        $existing = $this->templateModel->find((int)$id);
        if (!$existing || (!Auth::isSuperAdmin() && (int)$existing['org_id'] !== (int)Auth::orgId())) {
            $this->setFlash('error', 'Template not found.');
            $this->redirect('/reports/templates');
        }

        $this->templateModel->delete((int)$id);
        logAudit('report_template_deleted', 'reports', 'report_template', (int)$id);
        $this->setFlash('success', 'Template deleted successfully.');
        $this->redirect('/reports/templates');
    }
}
