<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';

header('Content-Type: application/json');
auth_require_login();

if (!gp_is_admin_like()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Permission denied.']);
    exit;
}

$id       = (int)($_POST['id'] ?? 0);
$paidDate = trim((string)($_POST['paid_date'] ?? ''));
$action   = trim((string)($_POST['action'] ?? 'pay')); // 'pay' or 'unpay'

if ($id <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Invalid ID.']);
    exit;
}

$pdo = crm_pdo();

if ($action === 'unpay') {
    $stmt = $pdo->prepare("UPDATE project_partners SET status = 'done', paid_amount = NULL, paid_date = NULL WHERE id = ?");
    $stmt->execute([$id]);
    echo json_encode(['ok' => true, 'status' => 'done', 'label' => 'Αναίρεση εξόφλησης']);
    exit;
}

// Validate date
if ($paidDate === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $paidDate)) {
    $paidDate = date('Y-m-d');
}

// Get agreed cost to set paid_amount
$row = $pdo->prepare("SELECT agreed_cost, paid_amount FROM project_partners WHERE id = ?");
$row->execute([$id]);
$partner = $row->fetch();
if (!$partner) {
    echo json_encode(['ok' => false, 'error' => 'Record not found.']);
    exit;
}

// Set paid_amount = agreed_cost if not already set
$paidAmount = (float)($partner['agreed_cost'] ?? $partner['paid_amount'] ?? 0);

$stmt = $pdo->prepare("
    UPDATE project_partners
    SET status = 'paid', paid_amount = :amount, paid_date = :paid_date
    WHERE id = :id
");
$stmt->execute([
    ':amount'    => $paidAmount > 0 ? $paidAmount : null,
    ':paid_date' => $paidDate,
    ':id'        => $id,
]);

gp_log_action($pdo, 'PARTNER_PAID', 'project_partners', $id, "Marked as paid on $paidDate");

echo json_encode([
    'ok'       => true,
    'status'   => 'paid',
    'paid_date'=> $paidDate,
    'amount'   => $paidAmount,
]);
