<?php
// Controllers/TaskController.php

require_once __DIR__ . '/../_Core/Validator.php';

class TaskController
{
    protected $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function createOrUpdate($data, $user)
    {
        $validated = $this->validateTask($data);

        if ($validated['error']) {
            return ['error' => true, 'msg' => $validated['msg']];
        }

        $payload = $validated['data'];
        $payload['created_by'] = $user['id'];

        if (!empty($data['id'])) {
            return $this->updateTask($data['id'], $payload);
        }

        return $this->createTask($payload);
    }

    private function validateTask($data)
    {
        $errors = [];

        $cid = Validator::id($data['customer_id'] ?? 0);
        if (!$cid) $errors[] = "Invalid Customer ID.";

        $title = Validator::str($data['title'] ?? "", 3, 120);
        $desc  = Validator::optionalStr($data['description'] ?? "", 255);

        $dueDate = Validator::date($data['due_date'] ?? "");
        if (!$dueDate) $errors[] = "Invalid due date.";

        $status = Validator::str($data['status'] ?? "Pending", 3, 50);

        if ($errors) {
            return ['error' => true, 'msg' => implode(" ", $errors)];
        }

        return [
            'error' => false,
            'data' => [
                'customer_id' => $cid,
                'title' => $title,
                'description' => $desc,
                'due_date' => $dueDate,
                'status' => $status
            ]
        ];
    }

    private function createTask($payload)
    {
        $sql = "INSERT INTO sd_tasks
                (customer_id, title, description, due_date, status, created_by, created_at)
                VALUES
                (:cid, :title, :desc, :due_date, :status, :created_by, NOW())";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([
            ':cid' => $payload['customer_id'],
            ':title' => $payload['title'],
            ':desc' => $payload['description'],
            ':due_date' => $payload['due_date'],
            ':status' => $payload['status'],
            ':created_by' => $payload['created_by'],
        ]);

        return ['error' => false, 'msg' => 'Task created successfully'];
    }

    private function updateTask($id, $payload)
    {
        $sql = "UPDATE sd_tasks
                SET title = :title,
                    description = :desc,
                    due_date = :due_date,
                    status = :status
                WHERE id = :id";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([
            ':id' => $id,
            ':title' => $payload['title'],
            ':desc' => $payload['description'],
            ':due_date' => $payload['due_date'],
            ':status' => $payload['status'],
        ]);

        return ['error' => false, 'msg' => 'Task updated successfully'];
    }
}
