<?php
// POST /api/cashflow/income.php
// action: add | update | delete | toggle_paid
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user    = requireAuth();
$db      = getDB();
$action  = post('action', 'add');
$isAdmin = in_array($user['role_id'], [1, 5]);

// Verify month is active
function assertActive(PDO $db, int $monthId): void {
    $s = $db->prepare("SELECT status FROM cashflow_months WHERE id = ? LIMIT 1");
    $s->execute([$monthId]);
    $m = $s->fetch();
    if (!$m || $m['status'] === 'closed') apiError('This month is closed and cannot be edited.', 403);
}

if ($action === 'add') {
    $monthId = (int)post('month_id', 0);
    assertActive($db, $monthId);
    $db->prepare("INSERT INTO cashflow_income (month_id, type, description, expected_amount, actual_amount, client_id, job_card_id, project_id, is_recurring, recur_end_month)
        VALUES (?,?,?,?,?,?,?,?,?,?)")
       ->execute([
           $monthId,
           post('type', 'planned'),
           post('description', ''),
           post('expected_amount') ?: null,
           post('actual_amount') ?: null,
           post('client_id') ?: null,
           post('job_card_id') ?: null,
           post('project_id') ?: null,
           post('is_recurring', 0),
           post('recur_end_month') ?: null,
       ]);
    apiSuccess(['id' => (int)$db->lastInsertId()], 'Income line added.');
}

if ($action === 'update') {
    $id = (int)post('id', 0);
    $monthId = (int)post('month_id', 0);
    assertActive($db, $monthId);
    $db->prepare("UPDATE cashflow_income SET type=?, description=?, expected_amount=?, actual_amount=?, client_id=?, job_card_id=?, project_id=?, is_recurring=?, recur_end_month=? WHERE id=? AND month_id=?")
       ->execute([
           post('type', 'planned'),
           post('description', ''),
           post('expected_amount') ?: null,
           post('actual_amount') ?: null,
           post('client_id') ?: null,
           post('job_card_id') ?: null,
           post('project_id') ?: null,
           post('is_recurring', 0),
           post('recur_end_month') ?: null,
           $id, $monthId
       ]);
    apiSuccess([], 'Updated.');
}

if ($action === 'delete') {
    $id = (int)post('id', 0);
    $monthId = (int)post('month_id', 0);
    assertActive($db, $monthId);
    $db->prepare("DELETE FROM cashflow_income WHERE id=? AND month_id=?")->execute([$id, $monthId]);
    apiSuccess([], 'Deleted.');
}

if ($action === 'toggle_paid') {
    $id      = (int)post('id', 0);
    $monthId = (int)post('month_id', 0);
    assertActive($db, $monthId);
    $cur = $db->prepare("SELECT is_paid FROM cashflow_income WHERE id=? LIMIT 1");
    $cur->execute([$id]);
    $row = $cur->fetch();
    $newVal = $row ? ($row['is_paid'] ? 0 : 1) : 1;
    $db->prepare("UPDATE cashflow_income SET is_paid=?, paid_date=? WHERE id=? AND month_id=?")
       ->execute([$newVal, $newVal ? date('Y-m-d') : null, $id, $monthId]);
    apiSuccess(['is_paid' => $newVal], 'Toggled.');
}

apiError('Unknown action.', 422);