<?php

class TasksController extends BaseController
{
    protected $pdo;

    public function __construct($pdo = null)
    {
        parent::__construct();
        $this->pdo = $pdo ?: Database::getConnection();
    }

    public function index()
    {
        $this->authCheck();
        $tenantId = $_SESSION['tenant_id'];

        $filters = [
            'status'   => $_GET['status']   ?? 'all',
            'priority' => $_GET['priority'] ?? 'all',
            'search'   => trim($_GET['search'] ?? ''),
        ];

        $sql = "
            SELECT t.*
            FROM tasks t
            WHERE t.tenant_id = :tenant_id
        ";

        $params = ['tenant_id' => $tenantId];

        if ($filters['status'] !== 'all' && $filters['status'] !== '') {
            $sql .= " AND t.status = :status";
            $params['status'] = $filters['status'];
        }

        if ($filters['priority'] !== 'all' && $filters['priority'] !== '') {
            $sql .= " AND t.priority = :priority";
            $params['priority'] = $filters['priority'];
        }

        if ($filters['search'] !== '') {
            $sql .= " AND (t.title LIKE :search OR t.description LIKE :search)";
            $params['search'] = '%' . $filters['search'] . '%';
        }

        $sql .= " ORDER BY t.due_date IS NULL ASC, t.due_date ASC, t.created_at DESC";

        $stmt  = $this->pdo->prepare($sql);
        $stmt->execute($params);
        $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $this->render('pages/tasks/index', [
            'tasks'       => $tasks,
            'filters'     => $filters,
            'currentPage' => 'tasks',
            'pageTitle'   => 'Tasks - LeadIntelligence AI',
        ]);
    }

    public function create()
    {
        $this->authCheck();

        $this->render('pages/tasks/form', [
            'task'        => null,
            'mode'        => 'create',
            'currentPage' => 'tasks',
            'pageTitle'   => 'New Task - LeadIntelligence AI',
        ]);
    }

    public function store()
    {
        $this->authCheck();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Invalid request method';
            $this->redirect('/lead-management/public/app/tasks');
        }

        $title       = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $dueDate     = $_POST['due_date'] ?? null;
        $priority    = $_POST['priority'] ?? 'medium';
        $status      = 'pending';

        if ($title === '') {
            $_SESSION['error']     = 'Title is required';
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/tasks/create');
        }

        try {
            $stmt = $this->pdo->prepare("
                INSERT INTO tasks (
                    tenant_id, title, description, status, priority, due_date, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");

            $stmt->execute([
                $_SESSION['tenant_id'],
                $title,
                $description,
                $status,
                $priority,
                $dueDate ?: null
            ]);

            $_SESSION['success'] = 'Task created successfully';
            $this->redirect('/lead-management/public/app/tasks');
        } catch (Exception $e) {
            error_log("Task store error: " . $e->getMessage());
            $_SESSION['error']     = 'Failed to create task';
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/tasks/create');
        }
    }

    public function show($id)
    {
        $this->authCheck();
        $task = $this->getTask($id);

        if (!$task) {
            $_SESSION['error'] = 'Task not found';
            $this->redirect('/lead-management/public/app/tasks');
        }

        $this->render('pages/tasks/show', [
            'task'        => $task,
            'currentPage' => 'tasks',
            'pageTitle'   => $task['title'] . ' - Task Details',
        ]);
    }

    public function edit($id)
    {
        $this->authCheck();
        $task = $this->getTask($id);

        if (!$task) {
            $_SESSION['error'] = 'Task not found';
            $this->redirect('/lead-management/public/app/tasks');
        }

        $this->render('pages/tasks/form', [
            'task'        => $task,
            'mode'        => 'edit',
            'currentPage' => 'tasks',
            'pageTitle'   => 'Edit Task - LeadIntelligence AI',
        ]);
    }

    public function update($id)
    {
        $this->authCheck();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Invalid request method';
            $this->redirect('/lead-management/public/app/tasks/' . $id . '/edit');
        }

        $task = $this->getTask($id);
        if (!$task) {
            $_SESSION['error'] = 'Task not found';
            $this->redirect('/lead-management/public/app/tasks');
        }

        $title       = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $dueDate     = $_POST['due_date'] ?? null;
        $priority    = $_POST['priority'] ?? 'medium';
        $status      = $_POST['status'] ?? 'pending';

        if ($title === '') {
            $_SESSION['error']     = 'Title is required';
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/tasks/' . $id . '/edit');
        }

        try {
            $stmt = $this->pdo->prepare("
                UPDATE tasks 
                SET title = ?, description = ?, status = ?, priority = ?, due_date = ?, updated_at = NOW()
                WHERE id = ? AND tenant_id = ?
            ");

            $stmt->execute([
                $title,
                $description,
                $status,
                $priority,
                $dueDate ?: null,
                $id,
                $_SESSION['tenant_id']
            ]);

            $_SESSION['success'] = 'Task updated successfully';
            $this->redirect('/lead-management/public/app/tasks');
        } catch (Exception $e) {
            error_log("Task update error: " . $e->getMessage());
            $_SESSION['error']     = 'Failed to update task';
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/tasks/' . $id . '/edit');
        }
    }

    public function delete($id)
    {
        $this->authCheck();
        $task = $this->getTask($id);

        if (!$task) {
            $_SESSION['error'] = 'Task not found';
            $this->redirect('/lead-management/public/app/tasks');
        }

        try {
            $stmt = $this->pdo->prepare("
                DELETE FROM tasks WHERE id = ? AND tenant_id = ?
            ");
            $stmt->execute([$id, $_SESSION['tenant_id']]);

            $_SESSION['success'] = 'Task deleted successfully';
        } catch (Exception $e) {
            error_log("Task delete error: " . $e->getMessage());
            $_SESSION['error'] = 'Failed to delete task';
        }

        $this->redirect('/lead-management/public/app/tasks');
    }

    // ============ helpers ============

    private function getTask($id)
    {
        try {
            $stmt = $this->pdo->prepare("
                SELECT * FROM tasks 
                WHERE id = ? AND tenant_id = ?
            ");
            $stmt->execute([$id, $_SESSION['tenant_id']]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log("getTask error: " . $e->getMessage());
            return null;
        }
    }
}
