<?php


// LeadController.
require_once __DIR__ . '/../../vendor/PhpSpreadsheet/Autoloader.php';

require_once __DIR__ . '/../../vendor/PhpSpreadsheet/src/PhpSpreadsheet/Spreadsheet.php';
require_once __DIR__ . '/../../vendor/PhpSpreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php';
require_once __DIR__ . '/../../vendor/PhpSpreadsheet/src/PhpSpreadsheet/Reader/Xls.php';
require_once __DIR__ . '/../../vendor/PhpSpreadsheet/src/PhpSpreadsheet/IOFactory.php';


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;


class LeadController extends Controller{
    
    public function index()
    {
        // Ensure session is started
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        // Redirect to login if not logged in
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $userId = $_SESSION['user_id'];
        $role = $_SESSION['user_role'];

        // Load Lead model
        $leadModel = $this->model('Lead');

        // Pagination setup
        $limit = 10; // number of leads per page
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $offset = ($page - 1) * $limit;

        // Fetch paginated leads
        $leads = $leadModel->getLeadsPaginated($userId, $role, $limit, $offset);

        // Count total leads for pagination
        $totalLeads = $leadModel->countLeads($userId, $role);
        $totalPages = ceil($totalLeads / $limit);

        // Load view
        $this->view('leads/index', [
            'leads' => $leads,
            'role' => $role,
            'currentPage' => $page,
            'totalPages' => $totalPages
        ]);
    }
    
    public function import(){
        
        
        session_start();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) {
            $file = $_FILES['excel_file']['tmp_name'];

            try {
                $spreadsheet = IOFactory::load($file);
                $sheet = $spreadsheet->getActiveSheet();
                $rows = $sheet->toArray();

                $leadModel = $this->model('Lead');
                $imported = 0;

                foreach ($rows as $index => $row) {
                    if ($index === 0) continue; // Skip header row

                    $data = [
                        'user_id' => trim($row[0]),
                        'name' => trim($row[1]),
                        'email' => trim($row[2]),
                        'phone' => trim($row[3]),
                        'source' => trim($row[4] ?? 'Unknown')
                    ];

                    if (!empty($data['name']) && !empty($data['email'])) {
                        $leadModel->addLead($data);
                        $imported++;
                    }
                }

                $success = "✅ Successfully imported {$imported} leads.";
                $this->view('leads/import', ['success' => $success]);
            } catch (Exception $e) {
                $error = "❌ Error reading file: " . $e->getMessage();
                $this->view('leads/import', ['error' => $error]);
            }
        } else {
            $this->view('leads/import', ['error' => 'No file uploaded.']);
        }
    }
    
    public function add(){
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['user_id'])) {
        header("Location: " . BASE_URL . "/LoginController/index");
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = [
            'user_id' => $_SESSION['user_id'],
            'name'    => trim($_POST['name']),
            'email'   => trim($_POST['email']),
            'phone'   => trim($_POST['phone']),
            'source'  => trim($_POST['source']),
        ];

        $leadModel = $this->model('Lead');

        if ($leadModel->addLead($data)) {
            $_SESSION['success'] = 'Lead added successfully.';
            header("Location: " . BASE_URL . "/lead/");
            exit;
        } else {
            $_SESSION['error'] = 'Failed to add lead.';
            $this->view('leads/add', ['data' => $data]);
            return;
        }
    }

    $this->view('leads/add');
}

    public function edit($id = null){
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['user_id']) || !$id) {
        header("Location: " . BASE_URL . "/login/index");
        exit;
    }

    $leadModel = $this->model('Lead');
    $lead = $leadModel->getLeadById($id);

    if (!$lead) {
        header("Location: " . BASE_URL . "/leads");
        exit;
    }

    // Check ownership for non-admins
    if (strtolower($_SESSION['user_role']) !== 'admin' && $lead['user_id'] != $_SESSION['user_id']) {
        header("Location: " . BASE_URL . "/lead");
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = [
            'name' => trim($_POST['name']),
            'email' => trim($_POST['email']),
            'phone' => trim($_POST['phone']),
            'source' => trim($_POST['source'])  // Fixed key from 'company' to 'source'
        ];

        if ($leadModel->updateLead($id, $data)) {
            $_SESSION['success'] = 'Lead updated successfully.';
            header("Location: " . BASE_URL . "/lead");
            exit;
        } else {
            $this->view('leads/edit', ['error' => 'Failed to update lead', 'lead' => $lead]);
            return;
        }
    }

    $this->view('leads/edit', ['lead' => $lead]);
}

public function delete($id = null)
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['user_id']) || !$id) {
        header("Location: " . BASE_URL . "/login/index");
        exit;
    }

    $leadModel = $this->model('Lead');
    $lead = $leadModel->getLeadById($id);

    if (!$lead) {
        $_SESSION['error'] = 'Lead not found.';
        header("Location: " . BASE_URL . "/lead");
        exit;
    }

    // Check ownership for non-admins
    if (strtolower($_SESSION['user_role']) !== 'admin' && $lead['user_id'] != $_SESSION['user_id']) {
        $_SESSION['error'] = 'You do not have permission to delete this lead.';
        header("Location: " . BASE_URL . "/lead");
        exit;
    }

    if ($leadModel->deleteLead($id)) {
        $_SESSION['success'] = 'Lead deleted successfully.';
    } else {
        $_SESSION['error'] = 'Failed to delete lead.';
    }

    header("Location: " . BASE_URL . "/lead");
    exit;
}



}
