<?php

namespace App\Modules\Frontend\Controllers;

use App\Controllers\BaseController;
use App\Modules\Frontend\Models\LeadModel;

class LeadController extends BaseController
{
    public function capture()
    {
        $rules = [
            'email' => 'required|valid_email',
            'purpose' => 'required|in_list[packing_list,newsletter]'
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Invalid input'
            ]);
        }

        $ip = $this->request->getIPAddress();
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            $ip = '0.0.0.0';
        }

        $leadModel = new LeadModel();
        $leadData = [
            'email' => $this->request->getPost('email'),
            'purpose' => $this->request->getPost('purpose'),
            'ip_address' => $ip
        ];

        try {
            if ($leadModel->insert($leadData)) {
                $purpose = $leadData['purpose'];

                // Send auto-response
                $email = service('email');
                $email->setFrom(setting('email.fromEmail'), setting('email.fromName'));
                $email->setTo($leadData['email']);
                $email->setSubject('Your Mount Kenya Resource');

                if ($purpose === 'packing_list') {
                    $message = "Thank you! Download your packing list here:\n" .
                               base_url('uploads/guides/Mount_Kenya_Packing_List.pdf');
                    $email->setMessage($message);
                } else {
                    $email->setMessage("Thanks for subscribing to our newsletter!");
                }

                $email->send();

                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Check your email!'
                ]);
            }
        } catch (\Exception $e) {
            log_message('error', 'Lead capture failed: ' . $e->getMessage());
        }

        return $this->response->setJSON([
            'status' => 'error',
            'message' => 'Failed to process request'
        ]);
    }
}