<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Csrf;
use App\Repositories\Container;

/**
 * Public-facing intake form flow. The customer receives a resume link by
 * email after booking, clicks it, and fills out medical + waiver + body
 * diagram without needing to log in. They do NOT sign here — the signature
 * is captured in person at the shop by staff on the iPad.
 */
class CustomerIntakeController
{
    public function show(array $params): void
    {
        $token = $params['token'] ?? '';
        $form  = Container::intakeForms()->findByResumeToken($token);
        if (!$form) {
            http_response_code(404);
            echo view('layouts.public', [
                'title' => 'Link expired',
                'content' => '<section class="pt-32 pb-28 max-w-xl mx-auto px-6 text-center">
                    <div class="text-xs uppercase tracking-[0.3em] text-gold">404</div>
                    <h1 class="mt-4 text-4xl font-display">Link expired or not found</h1>
                    <p class="mt-4 text-bone/60">This intake form link is no longer valid. Please contact us if you need help.</p>
                    <a href="' . url('/') . '" class="btn-gold mt-8 inline-block">Back to home</a>
                </section>',
            ]);
            return;
        }

        $customer = !empty($form['customer_id']) ? Container::users()->find($form['customer_id']) : null;
        $appointment = null;
        foreach (Container::appointments()->all() as $a) {
            if (($a['intake_form_id'] ?? null) === $form['id']) { $appointment = $a; break; }
        }
        $artist = (!empty($appointment['artist_id']))
            ? Container::artists()->find($appointment['artist_id'])
            : null;

        $clauses = \App\Controllers\HubFormsController::waiverClauses();
        $conditions = \App\Controllers\HubFormsController::medicalConditions();

        render('public', 'customer.intake', compact('form', 'customer', 'appointment', 'artist', 'clauses', 'conditions'), 'Your intake form');
    }

    public function save(array $params): void
    {
        Csrf::requireValid();
        $token = $params['token'] ?? '';
        $form  = Container::intakeForms()->findByResumeToken($token);
        if (!$form) {
            http_response_code(404);
            echo 'Form not found.';
            return;
        }
        if (($form['status'] ?? '') === 'SIGNED') {
            // Locked — can't edit after in-person signature
            redirect('/intake/' . $token . '?locked=1');
        }

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

        $updated = 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'              => 'SUBMITTED',
        ]);
        Container::intakeForms()->save($updated);

        // Also mirror general info into the User record so staff search picks it up
        if (!empty($form['customer_id'])) {
            $customer = Container::users()->find($form['customer_id']);
            if ($customer) {
                Container::users()->save(array_merge($customer, [
                    'first_name'    => $gi['first_name']    ?? $customer['first_name'],
                    'last_name'     => $gi['last_name']     ?? $customer['last_name'],
                    'email'         => $gi['email']         ?? $customer['email'],
                    'phone'         => $gi['phone']         ?? $customer['phone'],
                    'address_line'  => $gi['address']       ?? ($customer['address_line'] ?? null),
                    'city'          => $gi['city']          ?? $customer['city'],
                    'state'         => $gi['state']         ?? $customer['state'],
                    'zip'           => $gi['zip']           ?? $customer['zip'],
                    'date_of_birth' => $gi['date_of_birth'] ?? $customer['date_of_birth'],
                ]));
            }
        }

        // Show a full confirmation page
        $customer = !empty($form['customer_id']) ? Container::users()->find($form['customer_id']) : null;
        $appointment = null;
        foreach (Container::appointments()->all() as $a) {
            if (($a['intake_form_id'] ?? null) === $updated['id'] || ($a['intake_form_id'] ?? null) === ($form['id'] ?? '')) {
                $appointment = $a;
                break;
            }
        }
        $artist = (!empty($appointment['artist_id']))
            ? Container::artists()->find($appointment['artist_id'])
            : null;
        $form = $updated;
        render('public', 'customer.intake-confirmed', compact('form', 'customer', 'appointment', 'artist', 'token'), t('intake.confirmed.title'));
    }
}
