<?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', 'unpay', or 'save_payment'

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

$pdo = crm_pdo();

if ($action === 'save_payment') {
    $status     = trim((string)($_POST['status'] ?? 'done'));
    $paidAmount = isset($_POST['paid_amount']) ? (float)$_POST['paid_amount'] : 0.0;
    $notes      = trim((string)($_POST['notes'] ?? ''));

    if ($status !== 'paid' && $status !== 'done') {
        echo json_encode(['ok' => false, 'error' => 'Invalid status.']);
        exit;
    }

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

    // Set fields depending on partial vs full vs unpaid
    $dbAmount = ($paidAmount > 0) ? $paidAmount : null;
    $dbDate   = ($paidAmount > 0) ? $paidDate : null;

    $stmt = $pdo->prepare("
        UPDATE project_partners
        SET status = :status,
            paid_amount = :amount,
            paid_date = :paid_date,
            notes = :notes
        WHERE id = :id
    ");
    $stmt->execute([
        ':status'    => $status,
        ':amount'    => $dbAmount,
        ':paid_date' => $dbDate,
        ':notes'     => $notes !== '' ? $notes : null,
        ':id'        => $id,
    ]);

    gp_log_action($pdo, 'PARTNER_PAID_UPDATE', 'project_partners', $id, "Updated payment: Status=$status, Paid=$paidAmount, Date=$paidDate");

    echo json_encode([
        'ok'          => true,
        'status'      => $status,
        'paid_amount' => $paidAmount,
        'paid_date'   => $paidDate,
    ]);
    exit;
}

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,
]);
