<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Auth;
use App\Csrf;
use App\Pin;
use App\Repositories\Container;

class HubFormsController
{
    public function index(): void
    {
        $status = $_GET['status'] ?? '';
        $list = $status ? Container::intakeForms()->all(['status' => $status]) : Container::intakeForms()->all();
        render('hub', 'hub.forms', compact('list', 'status'), t('hub.forms.title'));
    }

    public function create(): void
    {
        // Create blank form + optional customer linkage
        $form = Container::intakeForms()->save([
            'status' => 'DRAFT',
            'general_info' => [],
            'medical_conditions' => [],
        ]);
        redirect('/hub/forms/' . $form['id']);
    }

    public function show(array $params): void
    {
        $form = Container::intakeForms()->find($params['id'] ?? '');
        if (!$form) { http_response_code(404); require MAT_ROOT . '/src/Views/errors/404.php'; return; }
        $customer = !empty($form['customer_id']) ? Container::users()->find($form['customer_id']) : null;
        $clauses = self::waiverClauses();
        $conditions = self::medicalConditions();
        render('hub', 'hub.form-editor', compact('form', 'customer', 'clauses', 'conditions'), t('hub.form.title'));
    }

    public function save(array $params): void
    {
        Csrf::requireValid();
        $form = Container::intakeForms()->find($params['id'] ?? '');
        if (!$form) { redirect('/hub/forms'); }

        $gi = (array)($form['general_info'] ?? []);
        foreach (['first_name','last_name','email','phone','address','city','state','zip','date_of_birth','gender','ethnicity','occupation','referral_source','sessions_needed','confidentiality'] as $f) {
            if (isset($_POST[$f])) $gi[$f] = trim((string)$_POST[$f]);
        }
        foreach (['emergency_contact_name','emergency_contact_phone','relationship'] as $f) {
            if (isset($_POST[$f])) $gi[$f] = trim((string)$_POST[$f]);
        }

        $form = Container::intakeForms()->save(array_merge($form, [
            'general_info' => $gi,
            'medical_conditions' => $_POST['medical_conditions'] ?? [],
            'medical_other'      => trim((string)($_POST['medical_other'] ?? '')),
            'on_medication'      => !empty($_POST['on_medication']),
            'medication_notes'   => trim((string)($_POST['medication_notes'] ?? '')),
            'waiver_initials'    => (array)($_POST['waiver_initials'] ?? []),
            'body_part'          => trim((string)($_POST['body_part'] ?? '')),
            'body_diagram_marks' => json_decode((string)($_POST['body_diagram_marks'] ?? '[]'), true) ?: [],
            'pigments'           => trim((string)($_POST['pigments'] ?? '')),
            'aftercare_acknowledged' => !empty($_POST['aftercare_acknowledged']),
            'status' => $form['status'] === 'DRAFT' ? 'SUBMITTED' : $form['status'],
        ]));
        $_SESSION['_flash']['success'] = t('hub.form.saved');
        redirect('/hub/forms/' . $form['id']);
    }

    public function sign(array $params): void
    {
        Csrf::requireValid();
        $form = Container::intakeForms()->find($params['id'] ?? '');
        if (!$form) { redirect('/hub/forms'); }

        $staff = Pin::authenticate((string)($_POST['username'] ?? ''), (string)($_POST['pin'] ?? ''));
        if (!$staff) {
            $_SESSION['_flash']['error'] = t('hub.pin.invalid');
            redirect('/hub/forms/' . $form['id']);
        }

        // Persist the customer signature PNG
        $sigDataUrl = (string)($_POST['signature_data'] ?? '');
        $sigUrl = null;
        if (str_starts_with($sigDataUrl, 'data:image/png;base64,')) {
            $png = base64_decode(substr($sigDataUrl, strlen('data:image/png;base64,')));
            if ($png) {
                $name = uuid() . '.png';
                $dest = config('upload_path') . '/signatures/' . $name;
                file_put_contents($dest, $png);
                $sigUrl = config('upload_url') . '/signatures/' . $name;
            }
        }

        // Sign action ALSO saves all the current form fields so no data is lost
        $gi = (array)($form['general_info'] ?? []);
        foreach ([
            'first_name','last_name','email','phone','address','city','state','zip',
            'date_of_birth','gender','ethnicity','occupation','sessions_needed',
            'emergency_contact_name','emergency_contact_phone','relationship','referral_source',
        ] as $f) {
            if (isset($_POST[$f]) && $_POST[$f] !== '') $gi[$f] = trim((string)$_POST[$f]);
        }

        $payload = array_merge($form, [
            'general_info'            => $gi,
            'medical_conditions'      => $_POST['medical_conditions'] ?? ($form['medical_conditions'] ?? []),
            'medical_other'           => isset($_POST['medical_other']) ? trim((string)$_POST['medical_other']) : ($form['medical_other'] ?? ''),
            'on_medication'           => isset($_POST['on_medication']) ? !empty($_POST['on_medication']) : ($form['on_medication'] ?? false),
            'medication_notes'        => isset($_POST['medication_notes']) ? trim((string)$_POST['medication_notes']) : ($form['medication_notes'] ?? ''),
            'waiver_initials'         => (array)($_POST['waiver_initials'] ?? ($form['waiver_initials'] ?? [])),
            'body_part'               => isset($_POST['body_part']) ? trim((string)$_POST['body_part']) : ($form['body_part'] ?? ''),
            'body_diagram_marks'      => isset($_POST['body_diagram_marks']) ? (json_decode((string)$_POST['body_diagram_marks'], true) ?: []) : ($form['body_diagram_marks'] ?? []),
            'pigments'                => isset($_POST['pigments']) ? trim((string)$_POST['pigments']) : ($form['pigments'] ?? ''),
            'aftercare_acknowledged'  => isset($_POST['aftercare_acknowledged']) ? !empty($_POST['aftercare_acknowledged']) : ($form['aftercare_acknowledged'] ?? false),
            'status'                  => 'SIGNED',
            'signed_at'               => now_iso(),
            'signed_with_staff_id'    => $staff['id'],
            'customer_signature_url'  => $sigUrl ?: ($form['customer_signature_url'] ?? null),
        ]);

        $form = Container::intakeForms()->save($payload);
        Container::audit()->log($staff['id'], 'SIGN_INTAKE', 'intake_form', $form['id']);
        $_SESSION['_flash']['success'] = t('hub.form.signed');
        redirect('/hub/forms/' . $form['id']);
    }

    public static function waiverClauses(): array
    {
        return ['c1','c2','c3','c4','c5','c6','c7','c8'];
    }

    public static function medicalConditions(): array
    {
        return [
            'heart_disease','diabetes','hypertension','mitral_valve_prolapse','cancer',
            'asthma','obesity','thyroid_disease','aids_hiv_positive',
            'healing_problems','keloid','seizures','dermatological_disorder',
            'hemophilia','autoimmune','allergies',
        ];
    }
}
