<?php
class LeadController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $search = $_GET['search'] ?? ''; $status = $_GET['status'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];
        $where = "WHERE l.deleted_at IS NULL AND l.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (l.first_name LIKE ? OR l.last_name LIKE ? OR l.email LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s]); }
        if ($status) { $where .= " AND l.status = ?"; $params[] = $status; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM leads l $where", $params);
        $offset = ($page - 1) * $perPage;
        $leads = $this->db->fetchAll("SELECT l.*, p.name as desired_property_name, u.first_name as agent_first, u.last_name as agent_last FROM leads l LEFT JOIN properties p ON l.desired_property_id=p.id LEFT JOIN users u ON l.assigned_agent_id=u.id $where ORDER BY l.created_at DESC LIMIT $perPage OFFSET $offset", $params);
        $stats = [
            'new' => $this->db->fetchColumn("SELECT COUNT(*) FROM leads WHERE company_id=? AND status='new' AND deleted_at IS NULL", [$cid]),
            'tour_scheduled' => $this->db->fetchColumn("SELECT COUNT(*) FROM leads WHERE company_id=? AND status='tour_scheduled' AND deleted_at IS NULL", [$cid]),
        ];
        $pagination = paginationHtml($total, $page, $perPage, '?page=leads');
        require 'app/views/leads/index.php';
    }

    public function create() {
        $lead = null; $cid = Auth::user()['company_id'];
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $agents = $this->db->fetchAll("SELECT id, first_name, last_name FROM users WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        require 'app/views/leads/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST); $v->required('first_name')->required('last_name');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=leads&action=create'); }
        $this->db->insert('leads', [
            'company_id' => Auth::user()['company_id'], 'first_name' => $_POST['first_name'],
            'last_name' => $_POST['last_name'], 'email' => $_POST['email'] ?? null, 'phone' => $_POST['phone'] ?? null,
            'desired_property_id' => $_POST['desired_property_id'] ?: null, 'desired_unit_id' => $_POST['desired_unit_id'] ?: null,
            'move_in_date' => $_POST['move_in_date'] ?: null, 'source' => $_POST['source'] ?? null,
            'status' => $_POST['status'] ?? 'new', 'assigned_agent_id' => $_POST['assigned_agent_id'] ?: null,
            'notes' => $_POST['notes'] ?? null,
        ]);
        flash('success', 'Lead created.'); redirect('?page=leads');
    }

    public function show($id) {
        $lead = $this->db->fetch("SELECT l.*, p.name as desired_property_name, u.first_name as agent_first, u.last_name as agent_last FROM leads l LEFT JOIN properties p ON l.desired_property_id=p.id LEFT JOIN users u ON l.assigned_agent_id=u.id WHERE l.id=? AND l.company_id=? AND l.deleted_at IS NULL", [$id, Auth::user()['company_id']]);
        if (!$lead) { flash('error', 'Lead not found.'); redirect('?page=leads'); }
        require 'app/views/leads/show.php';
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $lead = $this->db->fetch("SELECT * FROM leads WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$lead) { flash('error', 'Lead not found.'); redirect('?page=leads'); }
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $agents = $this->db->fetchAll("SELECT id, first_name, last_name FROM users WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        require 'app/views/leads/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $this->db->update('leads', [
            'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'],
            'email' => $_POST['email'] ?? null, 'phone' => $_POST['phone'] ?? null,
            'desired_property_id' => $_POST['desired_property_id'] ?: null,
            'move_in_date' => $_POST['move_in_date'] ?: null, 'source' => $_POST['source'] ?? null,
            'status' => $_POST['status'] ?? 'new', 'assigned_agent_id' => $_POST['assigned_agent_id'] ?: null,
            'notes' => $_POST['notes'] ?? null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Lead updated.'); redirect('?page=leads');
    }

    public function delete($id) {
        CSRF::verify();
        $this->db->softDelete('leads', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Lead deleted.'); redirect('?page=leads');
    }
}
