<?php
/**
 * BdmPlans — annual business-development plan.
 * MVP: header CRUD + list. Objective sub-rows deferred.
 */
class BdmPlans extends Model
{
    public function listAll(): array
    {
        $db = new DB();
        return $db->mySelect(
            "SELECT p.*, u.full_name AS owner_name,
                    (SELECT COUNT(*) FROM bdm_plan_objectives WHERE plan_id = p.c0d) AS objectives
               FROM bdm_plans p
          LEFT JOIN users u ON u.c0d = p.owner_id
              WHERE p.deleted = 0
              ORDER BY p.plan_year DESC, p.created_on DESC",
            []
        ) ?: [];
    }

    public function find(int $id): ?array
    {
        $db = new DB();
        $r = $db->mySelect("SELECT * FROM bdm_plans WHERE c0d = :id AND deleted = 0", [':id' => $id]);
        return $r[0] ?? null;
    }

    public function objectives(int $planId): array
    {
        $db = new DB();
        return $db->mySelect("SELECT * FROM bdm_plan_objectives WHERE plan_id = :id ORDER BY c0d", [':id' => $planId]) ?: [];
    }

    public function create(array $d, int $userId): int
    {
        $db = new DB();
        $fb = $db->insertUpdate(
            "INSERT INTO bdm_plans (plan_name, plan_year, target_amount, currency, status, owner_id, created_by, created_on)
             VALUES (:nm, :y, :ta, 'TZS', 'DRAFT', :o, :u, NOW())",
            [':nm' => (string)($d['plan_name'] ?? ''), ':y' => (int)($d['plan_year'] ?? date('Y')),
             ':ta' => (float)($d['target_amount'] ?? 0), ':o' => $userId, ':u' => $userId]
        );
        return (int)($fb['last_id'] ?? 0);
    }

    public function update(int $id, array $d, int $userId): void
    {
        $db = new DB();
        $db->insertUpdate(
            "UPDATE bdm_plans SET plan_name = :nm, plan_year = :y, target_amount = :ta,
                    status = :s, edited_by = :u, edited_on = NOW() WHERE c0d = :id",
            [':nm' => (string)($d['plan_name'] ?? ''), ':y' => (int)($d['plan_year'] ?? date('Y')),
             ':ta' => (float)($d['target_amount'] ?? 0), ':s' => (string)($d['status'] ?? 'DRAFT'),
             ':u' => $userId, ':id' => $id]
        );
    }

    public function addObjective(int $planId, string $objective, float $targetValue): int
    {
        $db = new DB();
        $fb = $db->insertUpdate(
            "INSERT INTO bdm_plan_objectives (plan_id, objective, target_value) VALUES (:p, :o, :t)",
            [':p' => $planId, ':o' => $objective, ':t' => $targetValue]
        );
        return (int)($fb['last_id'] ?? 0);
    }
}
