<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Franchisee Controller
 *
 * Handles the franchisee inquiry form display and submission.
 */
class FranchiseeController extends Controller
{
    /**
     * Display the franchisee inquiry form.
     *
     * @return void
     */
    public function index(): void
    {
        $settingModel = $this->model('Setting');
        $settings = $settingModel->getAll();

        $this->view('franchisee/index', [
            'title'      => 'Become a Franchisee - Gmind Institute',
            'settings'   => $settings,
            'currentPage' => 'franchisee',
        ]);
    }

    /**
     * Process the franchisee inquiry form submission.
     *
     * Validates CSRF token, sanitizes inputs, and inserts
     * a franchisee application record.
     *
     * @return void
     */
    public function store(): void
    {
        $this->validateCsrf();

        $name             = sanitize($_POST['name'] ?? '');
        $email            = sanitize($_POST['email'] ?? '');
        $phone            = sanitize($_POST['phone'] ?? '');
        $city             = sanitize($_POST['city'] ?? '');
        $state            = sanitize($_POST['state'] ?? '');
        $investmentRange  = sanitize($_POST['investment_range'] ?? '');
        $message          = sanitize($_POST['message'] ?? '');

        // Basic validation
        if (empty($name) || empty($email) || empty($phone) || empty($city) || empty($state)) {
            flash('error', 'Please fill in all required fields.');
            redirect('/franchisee');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address.');
            redirect('/franchisee');
        }

        try {
            $franchiseeModel = $this->model('Franchisee');
            $franchiseeModel->create([
                'name'             => $name,
                'email'            => $email,
                'phone'            => $phone,
                'city'             => $city,
                'state'            => $state,
                'investment_range' => $investmentRange,
                'message'          => $message,
                'status'           => 'pending',
            ]);

            flash('success', 'Your franchise inquiry has been submitted successfully! We will contact you soon.');
            redirect('/franchisee');
        } catch (\Throwable $e) {
            error_log('Franchisee submission error: ' . $e->getMessage());
            flash('error', 'Something went wrong. Please try again later.');
            redirect('/franchisee');
        }
    }
}
