<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Lead;
use App\Models\Course;

class LeadController {
    public function index() {
        if (!Auth::hasPermission('leads')) {
            redirect('/login');
            exit;
        }

        $leadModel = new Lead();
        $params = [
            'search' => $_GET['search'] ?? '',
            'status' => $_GET['status'] ?? '',
        ];

        $leads = $leadModel->search($params);
        $courseModel = new Course();
        $courses = $courseModel->search();
        
        $title = 'Lead Management';
        require_once __DIR__ . '/../../views/admin/leads/index.php';
    }

    public function view() {
        if (!Auth::hasPermission('leads')) {
            redirect('/login');
            exit;
        }

        if (!isset($_GET['id'])) {
            redirect('/admin/leads');
            exit;
        }

        $leadModel = new Lead();
        $lead = $leadModel->find($_GET['id']);
        
        if (!$lead) {
            redirect('/admin/leads');
            exit;
        }

        $followups = $leadModel->getFollowups($_GET['id']);
        $title = 'Lead Details: ' . $lead['name'];
        require_once __DIR__ . '/../../views/admin/leads/show.php';
    }

    public function save() {
        if (!Auth::hasPermission('leads')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $leadModel = new Lead();
            $data = [
                'id' => $_POST['id'] ?? null,
                'name' => $_POST['name'],
                'phone' => $_POST['phone'],
                'email' => $_POST['email'] ?: null,
                'source' => $_POST['source'] ?: null,
                'course_id' => $_POST['course_id'] ?: null,
                'status' => $_POST['status'] ?? 'New',
                'notes' => $_POST['notes'] ?? null,
            ];

            try {
                $leadId = $leadModel->save($data);
                $_SESSION['toast'] = ['message' => $data['id'] ? 'Lead updated!' : 'Lead created!', 'type' => 'success'];
                redirect('/admin/leads/view?id=' . $leadId);
                exit;
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/leads');
        exit;
    }

    public function addFollowup() {
        if (!Auth::hasPermission('leads')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $leadModel = new Lead();
            $data = [
                'lead_id' => $_POST['lead_id'],
                'interaction_date' => $_POST['interaction_date'] ?: date('Y-m-d H:i:s'),
                'type' => $_POST['type'],
                'notes' => $_POST['notes'],
                'next_reminder_date' => $_POST['next_reminder_date'] ?: null,
            ];

            try {
                $leadModel->addFollowup($data);
                
                // If status is also updated
                if (!empty($_POST['update_status'])) {
                    $leadModel->updateStatus($_POST['lead_id'], $_POST['update_status']);
                }

                $_SESSION['toast'] = ['message' => 'Follow-up recorded!', 'type' => 'success'];
                redirect('/admin/leads/view?id=' . $_POST['lead_id']);
                exit;
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect('/admin/leads');
        exit;
    }

    public function delete() {
        if (!Auth::hasPermission('leads')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            $leadModel = new Lead();
            $leadModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Lead removed.', 'type' => 'info'];
        }
        redirect('/admin/leads');
        exit;
    }
}
