<?php
// Controllers/FollowupController.php

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

class FollowupController
{
    protected $pdo;

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

    public function createOrUpdate($data, $user)
    {
        $validated = $this->validateFollowup($data);
        if ($validated['error']) {
            return ['error' => true, 'msg' => $validated['msg']];
        }

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

        // AUTO NEXT FOLLOW-UP DATE
        $payload['next_followup_date'] = FollowupScheduler::getNextDate($payload['followup_type']);

        // AUTO UPDATE CUSTOMER STATUS
        $this->updateCustomerStatus($payload['customer_id'], $payload['followup_type']);

        // CREATE vs UPDATE
        if (!empty($data['id'])) {
            return $this->updateFollowup($data['id'], $payload);
        }

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

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

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

        $type = Validator::str($data['followup_type'] ?? "", 3, 60);
        $note = Validator::optionalStr($data['note'] ?? "", 255);

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

        return [
            'error' => false,
            'data' => [
                'customer_id' => $cid,
                'followup_type' => $type,
                'note' => $note
            ]
        ];
    }

    private function updateCustomerStatus($cid, $followupType)
    {
        // fetch current status
        $c = $this->pdo->prepare("SELECT customer_status FROM sd_customers WHERE id = ?");
        $c->execute([$cid]);
        $curStatus = $c->fetchColumn();

        $next = FollowupScheduler::nextStatus($curStatus, $followupType);

        $u = $this->pdo->prepare("UPDATE sd_customers SET customer_status = ? WHERE id = ?");
        $u->execute([$next, $cid]);
    }

    private function createFollowup($payload)
    {
        $sql = "INSERT INTO sd_followups
                (customer_id, followup_type, note, next_followup_date, created_by, created_at)
                VALUES (:cid, :type, :note, :nfd, :created_by, NOW())";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([
            ':cid' => $payload['customer_id'],
            ':type' => $payload['followup_type'],
            ':note' => $payload['note'],
            ':nfd' => $payload['next_followup_date'],
            ':created_by' => $payload['created_by'],
        ]);

        return ['error' => false, 'msg' => 'Follow-up added successfully'];
    }

    private function updateFollowup($id, $payload)
    {
        $sql = "UPDATE sd_followups SET
                    followup_type = :type,
                    note = :note,
                    next_followup_date = :nfd
                WHERE id = :id";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([
            ':id' => $id,
            ':type' => $payload['followup_type'],
            ':note' => $payload['note'],
            ':nfd' => $payload['next_followup_date'],
        ]);

        return ['error' => false, 'msg' => 'Follow-up updated successfully'];
    }
}
