<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/access_guards.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
gp_require_staff_access($pdo);
$canViewCostings = gp_user_perm($pdo, 'perm_costings');

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { header('Location: /gopools/public/partners/index.php'); exit; }

$stmt = $pdo->prepare("SELECT * FROM external_partners WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$partner = $stmt->fetch();
if (!$partner) { header('Location: /gopools/public/partners/index.php'); exit; }

$page_title = $partner['company_name'] ?: $partner['contact_person'];

// ── 1. Jobs from project_partners (manual/billing records) ──
$stmt = $pdo->prepare("
    SELECT
        pp.id,
        pp.project_id,
        pp.work_date,
        pp.description,
        pp.agreed_cost,
        pp.paid_amount,
        pp.paid_date,
        pp.status,
        pp.notes,
        p.code,
        p.title  AS project_title,
        p.status AS project_status,
        p.city   AS project_city,
        'manual' AS source,
        ppc.quote_amount
    FROM project_partners pp
    LEFT JOIN projects p ON p.id = pp.project_id
    LEFT JOIN partner_project_costings ppc ON ppc.project_id = p.id AND ppc.external_partner_id = pp.external_partner_id
    WHERE pp.external_partner_id = :id
    ORDER BY pp.work_date DESC, pp.id DESC
");
$stmt->execute([':id' => $id]);
$manualRows = $stmt->fetchAll();

$manualProjectIds = array_column($manualRows, 'project_id');

// ── 2. Jobs from project_assignments (dispatches) ──
$stmtA = $pdo->prepare("
    SELECT
        pa.id,
        pa.project_id,
        pa.assigned_date AS work_date,
        pa.role_label    AS description,
        NULL             AS agreed_cost,
        NULL             AS paid_amount,
        NULL             AS paid_date,
        pa.status,
        pa.notes,
        p.code,
        p.title  AS project_title,
        p.status AS project_status,
        p.city   AS project_city,
        'dispatch' AS source,
        ppc.quote_amount
    FROM project_assignments pa
    LEFT JOIN projects p ON p.id = pa.project_id
    LEFT JOIN partner_project_costings ppc ON ppc.project_id = p.id AND ppc.external_partner_id = pa.external_partner_id
    WHERE pa.external_partner_id = :id
      AND pa.assignment_type = 'partner'
    ORDER BY pa.assigned_date DESC, pa.id DESC
");
$stmtA->execute([':id' => $id]);
$assignedRows = $stmtA->fetchAll();

// Filter out assignments if we already have a manual billing record for that project
$filteredAssignedRows = array_filter($assignedRows, function($r) use ($manualProjectIds) {
    return !in_array($r['project_id'], $manualProjectIds);
});

// Merge both sources
$allRows = array_merge($manualRows, $filteredAssignedRows);

// Sort merged rows by work_date descending
usort($allRows, function($a, $b) {
    return strcmp($b['work_date'] ?? '', $a['work_date'] ?? '');
});

// Split into pending/paid
$pendingRows = array_filter($allRows, fn($r) => $r['status'] !== 'paid' && $r['status'] !== 'cancelled');
$paidRows    = array_filter($allRows, fn($r) => $r['status'] === 'paid');
$cancelledRows = array_filter($allRows, fn($r) => $r['status'] === 'cancelled');

// Totals (fully supporting partial payments)
$totalAgreed  = 0;
$totalPaid    = 0;
$totalPending = 0;

$getCost = fn($r) => (float)(is_numeric($r['agreed_cost'] ?? null) ? $r['agreed_cost'] : ($r['quote_amount'] ?? 0));
$getPaid = fn($r) => (float)(is_numeric($r['paid_amount'] ?? null) && (float)$r['paid_amount'] > 0 
    ? $r['paid_amount'] 
    : (is_numeric($r['agreed_cost'] ?? null) ? $r['agreed_cost'] : ($r['quote_amount'] ?? 0)));

foreach ($allRows as $r) {
    if ($r['status'] === 'cancelled') {
        continue;
    }
    $cost = $getCost($r);
    $paid = (float)(is_numeric($r['paid_amount'] ?? null) ? $r['paid_amount'] : 0);
    
    if ($r['status'] === 'paid') {
        if ($paid == 0) {
            $paid = $cost;
        }
        $totalPaid += $paid;
    } else {
        $totalPaid += $paid;
        $totalPending += max($cost - $paid, 0);
    }
    $totalAgreed += $cost;
}

$activeTab = $_GET['tab'] ?? 'pending';

$statusColors = [
    'planned'  => '#8b5cf6',
    'working'  => '#f59e0b',
    'done'     => '#10b981',
    'paid'     => '#10b981',
    'cancelled'=> '#ef4444',
];
$statusLabels = [
    'planned'  => 'Προγραμματισμένο',
    'working'  => 'Σε εξέλιξη',
    'done'     => 'Ολοκληρώθηκε',
    'paid'     => 'Εξοφλήθηκε',
    'cancelled'=> 'Ακυρώθηκε',
];

include __DIR__ . '/../includes/header.php';
?>

<style>
.partner-hero {
  background: linear-gradient(135deg, var(--gp-primary) 0%, #6366f1 100%);
  border-radius: 20px; padding: 28px 32px; margin-bottom: 20px;
  color: #fff; display: flex; align-items: center; gap: 20px;
  position: relative; overflow: hidden;
}
.partner-hero::before {
  content: ''; position: absolute; top: -40px; right: -40px;
  width: 180px; height: 180px; border-radius: 50%;
  background: rgba(255,255,255,0.06);
}
.partner-hero-avatar {
  width: 64px; height: 64px; border-radius: 18px; flex-shrink: 0;
  background: rgba(255,255,255,0.15); display: flex; align-items: center;
  justify-content: center; font-size: 1.8rem; font-weight: 800;
  border: 2px solid rgba(255,255,255,0.3);
}
.partner-hero-name { font-size: 1.5rem; font-weight: 800; }
.partner-hero-sub  { font-size: .9rem; opacity: .8; margin-top: 4px; }

.billing-cards { display: grid; grid-template-columns: repeat(4,1fr); gap: 12px; margin-bottom: 20px; }
.billing-card {
  background: var(--gp-card-bg); border: 1px solid var(--gp-card-border);
  border-radius: 14px; padding: 16px 18px;
}
.billing-card-label { font-size: .72rem; font-weight: 700; text-transform: uppercase; letter-spacing: .07em; color: var(--gp-muted); }
.billing-card-value { font-size: 1.45rem; font-weight: 800; margin-top: 6px; }

.tab-bar { display: flex; gap: 4px; border-bottom: 2px solid var(--gp-card-border); margin-bottom: 16px; }
.tab-btn {
  padding: 10px 18px; font-size: .85rem; font-weight: 700; border: none;
  background: transparent; color: var(--gp-muted); cursor: pointer;
  border-bottom: 2px solid transparent; margin-bottom: -2px; transition: all .18s;
  text-decoration: none; display: inline-block;
}
.tab-btn.active { color: var(--gp-primary); border-bottom-color: var(--gp-primary); }
.tab-btn .tab-count {
  display: inline-flex; align-items: center; justify-content: center;
  width: 20px; height: 20px; border-radius: 999px; font-size: .68rem;
  background: rgba(0,0,0,.06); margin-left: 6px;
}
[data-theme='dark'] .tab-btn .tab-count { background: rgba(255,255,255,.08); }
.tab-btn.active .tab-count { background: rgba(37,99,235,.15); color: var(--gp-primary); }

.job-row { transition: background .15s; }
.job-row:hover { background: rgba(0,0,0,.015); }
[data-theme='dark'] .job-row:hover { background: rgba(255,255,255,.015); }

.status-pill {
  display: inline-flex; align-items: center; gap: 4px;
  padding: 3px 9px; border-radius: 999px; font-size: .72rem; font-weight: 700;
}

.job-row.clickable {
  cursor: pointer;
}
.job-row.clickable:hover {
  background: rgba(37, 99, 235, 0.04) !important;
}

/* Modern modal styles */
.gp-modal {
  display: none;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.5);
  backdrop-filter: blur(4px);
  align-items: center;
  justify-content: center;
}
.gp-modal.open {
  display: flex;
}
.gp-modal-content {
  background: var(--gp-card-bg);
  border: 1px solid var(--gp-card-border);
  border-radius: 16px;
  width: 100%;
  max-width: 480px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  animation: modalFadeIn 0.25s ease-out;
  padding: 24px;
}
@keyframes modalFadeIn {
  from { opacity: 0; transform: translateY(15px); }
  to { opacity: 1; transform: translateY(0); }
}
.gp-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.gp-modal-title {
  font-size: 1.15rem;
  font-weight: 800;
  color: var(--gp-text);
}
.gp-modal-close {
  background: transparent;
  border: none;
  font-size: 1.5rem;
  color: var(--gp-muted);
  cursor: pointer;
  line-height: 1;
}
.gp-modal-close:hover {
  color: var(--gp-text);
}

@media(max-width:768px) { .billing-cards { grid-template-columns: repeat(2,1fr); } }
@media(max-width:480px) { .billing-cards { grid-template-columns: 1fr 1fr; } }
</style>

<!-- Hero -->
<div class="partner-hero">
  <div class="partner-hero-avatar">
    <?php echo strtoupper(substr($partner['company_name'] ?: $partner['contact_person'] ?: 'P', 0, 1)); ?>
  </div>
  <div style="flex:1;min-width:0;">
    <div class="partner-hero-name"><?php echo h($partner['company_name'] ?: $partner['contact_person']); ?></div>
    <div class="partner-hero-sub">
      <?php echo h($partner['contact_person'] ?? ''); ?>
      <?php if ($partner['specialty']): ?> · <?php echo h($partner['specialty']); ?><?php endif; ?>
      <?php if ($partner['phone']): ?> · 📞 <?php echo h($partner['phone']); ?><?php endif; ?>
      <?php if ($partner['city']): ?> · 📍 <?php echo h($partner['city']); ?><?php endif; ?>
    </div>
  </div>
  <div style="display:flex;gap:8px;flex-shrink:0;">
    <a class="btn btn-sm" href="/gopools/public/partners/edit.php?id=<?php echo $id; ?>"
      style="background:rgba(255,255,255,.15);color:#fff;border-color:rgba(255,255,255,.3);">✏️ Επεξεργασία</a>
    <a class="btn btn-sm" href="/gopools/public/partners/index.php"
      style="background:rgba(255,255,255,.1);color:#fff;border-color:rgba(255,255,255,.2);">← Πίσω</a>
  </div>
</div>

<?php if ($canViewCostings): ?>
<!-- Billing Summary -->
<div class="billing-cards">
  <div class="billing-card">
    <div class="billing-card-label">Σύνολο Εργων</div>
    <div class="billing-card-value"><?php echo count($allRows); ?></div>
  </div>
  <div class="billing-card" style="border-color:rgba(239,68,68,.2);">
    <div class="billing-card-label">Εκκρεμεί</div>
    <div class="billing-card-value" style="color:#ef4444;">€ <?php echo number_format($totalPending, 2); ?></div>
  </div>
  <div class="billing-card" style="border-color:rgba(16,185,129,.2);">
    <div class="billing-card-label">Εξοφλήθηκε</div>
    <div class="billing-card-value" style="color:#10b981;">€ <?php echo number_format($totalPaid, 2); ?></div>
  </div>
  <div class="billing-card" style="border-color:rgba(37,99,235,.2);">
    <div class="billing-card-label">Συνολικό Ποσό</div>
    <div class="billing-card-value" style="color:var(--gp-primary);">€ <?php echo number_format($totalAgreed, 2); ?></div>
  </div>
</div>
<?php endif; ?>

<!-- Tabs -->
<div class="card">
  <div class="tab-bar">
    <a class="tab-btn <?php echo $activeTab === 'pending' ? 'active' : ''; ?>"
       href="?id=<?php echo $id; ?>&tab=pending">
      ⚡ Εκκρεμείς<span class="tab-count"><?php echo count($pendingRows); ?></span>
    </a>
    <a class="tab-btn <?php echo $activeTab === 'paid' ? 'active' : ''; ?>"
       href="?id=<?php echo $id; ?>&tab=paid">
      ✅ Εξοφλήθηκαν<span class="tab-count"><?php echo count($paidRows); ?></span>
    </a>
    <a class="tab-btn <?php echo $activeTab === 'all' ? 'active' : ''; ?>"
       href="?id=<?php echo $id; ?>&tab=all">
      📋 Όλα<span class="tab-count"><?php echo count($allRows); ?></span>
    </a>
  </div>

  <?php
  $displayRows = match($activeTab) {
      'paid'    => $paidRows,
      'all'     => $allRows,
      default   => $pendingRows,
  };
  ?>

  <?php if (empty($displayRows)): ?>
  <div style="text-align:center;padding:40px;color:var(--gp-muted);">
    <?php echo $activeTab === 'pending' ? '✅ Δεν υπάρχουν εκκρεμείς χρεώσεις!' : '— Δεν υπάρχουν εγγραφές —'; ?>
  </div>
  <?php else: ?>
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>Έργο</th>
          <th>Ημ. Εργασίας</th>
          <th>Περιγραφή</th>
          <?php if ($canViewCostings): ?>
          <th>Συμφωνηθέν</th>
          <?php if ($activeTab === 'paid' || $activeTab === 'all'): ?>
          <th>Πληρώθηκε</th>
          <th>Ημ. Εξόφλησης</th>
          <?php endif; ?>
          <?php endif; ?>
          <th>Status</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($displayRows as $r):
          $statusColor = $statusColors[$r['status']] ?? '#6b7280';
          $statusLabel = $statusLabels[$r['status']] ?? $r['status'];
          $isManual = ($r['source'] === 'manual');
        ?>
        <tr class="job-row <?php echo $isManual ? 'clickable' : ''; ?>"
            <?php if ($isManual): ?>
            data-payment-id="<?php echo (int)$r['id']; ?>"
            data-payment-code="<?php echo h($r['code'] ?? ''); ?>"
            data-payment-title="<?php echo h($r['project_title'] ?? ''); ?>"
            data-payment-agreed="<?php echo (float)$r['agreed_cost']; ?>"
            data-payment-paid="<?php echo (float)($r['paid_amount'] ?? 0); ?>"
            data-payment-date="<?php echo h($r['paid_date'] ?? ''); ?>"
            data-payment-status="<?php echo h($r['status']); ?>"
            data-payment-notes="<?php echo h($r['notes'] ?? ''); ?>"
            <?php endif; ?>>
          <td>
            <a href="/gopools/public/projects/view.php?id=<?php echo (int)$r['project_id']; ?>"
               style="font-weight:700;color:var(--gp-primary);text-decoration:none;font-size:.88rem;"
               title="Άνοιγμα έργου">
              <?php echo h($r['code'] ?? ''); ?>
            </a>
            <div style="font-size:.78rem;color:var(--gp-muted);"><?php echo h($r['project_title'] ?? ''); ?></div>
            <?php if ($r['project_city']): ?>
            <div style="font-size:.72rem;color:var(--gp-muted);">📍 <?php echo h($r['project_city']); ?></div>
            <?php endif; ?>
          </td>
          <td style="font-size:.85rem;white-space:nowrap;"><?php echo $r['work_date'] ? gp_date($r['work_date']) : '—'; ?></td>
          <td style="font-size:.83rem;max-width:200px;"><?php echo h($r['description'] ?? ''); ?></td>
          <?php if ($canViewCostings): ?>
          <td style="font-weight:700;">
            <?php if ($r['agreed_cost'] !== null && $r['agreed_cost'] !== ''): ?>
              € <?php echo number_format((float)$r['agreed_cost'], 2); ?>
              <?php if (!empty($r['quote_amount'])): ?>
                <div style="font-size:0.68rem; color:var(--gp-muted); margin-top:2px;">Quote: € <?php echo number_format((float)$r['quote_amount'], 2); ?></div>
              <?php endif; ?>
            <?php else: ?>
              <a href="/gopools/public/projects/partners.php?project_id=<?php echo (int)$r['project_id']; ?>" style="font-size:0.75rem; color:#f59e0b; text-decoration:none; border:1px solid rgba(245,158,11,0.5); padding:2px 6px; border-radius:6px; background:rgba(245,158,11,0.1);">✏️ Προσθήκη</a>
              <?php if (!empty($r['quote_amount'])): ?>
                <div style="font-size:0.7rem; color:var(--gp-primary); margin-top:4px; font-weight:800;">Quote: € <?php echo number_format((float)$r['quote_amount'], 2); ?></div>
              <?php endif; ?>
            <?php endif; ?>
          </td>
          <?php if ($activeTab === 'paid' || $activeTab === 'all'): ?>
          <td style="color:#10b981;font-weight:700;">
            <?php echo $r['paid_amount'] ? '€ ' . number_format((float)$r['paid_amount'], 2) : '—'; ?>
          </td>
          <td style="font-size:.83rem;white-space:nowrap;">
            <?php echo (!empty($r['paid_date']) && $r['paid_date'] !== '0000-00-00') ? gp_date($r['paid_date']) : '—'; ?>
          </td>
          <?php endif; ?>
          <?php endif; ?>
          <td>
            <span class="status-pill" style="background:<?php echo $statusColor; ?>1a;color:<?php echo $statusColor; ?>;border:1px solid <?php echo $statusColor; ?>33;">
              <?php echo h($statusLabel); ?>
            </span>
          </td>
          <td>
            <a href="/gopools/public/projects/view.php?id=<?php echo (int)$r['project_id']; ?>"
               class="btn btn-sm btn-outline-light" style="font-size:.75rem;">Έργο →</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <?php if ($canViewCostings && count($displayRows) > 1): ?>
      <tfoot>
        <tr style="background:var(--gp-nav-bg-2);font-weight:700;">
          <td colspan="3" style="font-size:.82rem;color:var(--gp-muted);">Σύνολο (<?php echo count($displayRows); ?> εγγραφές)</td>
          <td>€ <?php echo number_format(array_sum(array_map(fn($r) => (float)(is_numeric($r['agreed_cost'] ?? null) ? $r['agreed_cost'] : ($r['quote_amount'] ?? 0)), iterator_to_array(new ArrayIterator($displayRows)))), 2); ?></td>
          <?php if ($activeTab === 'paid' || $activeTab === 'all'): ?>
          <td style="color:#10b981;">€ <?php echo number_format(array_sum(array_map($getPaid, iterator_to_array(new ArrayIterator($displayRows)))), 2); ?></td>
          <td></td>
          <?php endif; ?>
          <td colspan="2"></td>
        </tr>
      </tfoot>
      <?php endif; ?>
    </table>
  </div>
  <?php endif; ?>
</div>

<!-- Payment Update Modal -->
<div id="paymentModal" class="gp-modal">
  <div class="gp-modal-content">
    <div class="gp-modal-header">
      <h3 class="gp-modal-title">💳 Ενημέρωση Πληρωμής</h3>
      <button class="gp-modal-close" onclick="closePaymentModal()">&times;</button>
    </div>
    <form id="paymentForm" onsubmit="submitPaymentForm(event)">
      <input type="hidden" id="modalPaymentId">
      
      <div style="margin-bottom: 16px; padding: 12px; background: rgba(37,99,235,0.04); border: 1px solid var(--gp-card-border); border-radius: 8px;">
        <div style="font-size: 0.75rem; font-weight: 700; text-transform: uppercase; color: var(--gp-muted);">Έργο</div>
        <div id="modalProjectName" style="font-weight: 800; font-size: 0.95rem; margin-top: 2px;"></div>
        <div style="display: flex; justify-content: space-between; margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--gp-card-border);">
          <span style="font-size: 0.8rem; color: var(--gp-muted);">Συμφωνηθέν Ποσό:</span>
          <span id="modalAgreedCost" style="font-weight: 800; font-size: 0.9rem;"></span>
        </div>
      </div>

      <div class="form-group" style="margin-bottom: 14px;">
        <label style="font-weight: 700; font-size: 0.8rem; margin-bottom: 6px; display: block;">Κατάσταση Πληρωμής</label>
        <select id="modalPaymentType" onchange="handlePaymentTypeChange()" class="form-control" style="width: 100%; padding: 8px; border-radius: 8px; border: 1px solid var(--gp-card-border); background: var(--gp-card-bg); color: var(--gp-text);">
          <option value="unpaid">❌ Ανεξόφλητο / Εκκρεμεί</option>
          <option value="partial">⏳ Μερική Εξόφληση</option>
          <option value="full">✅ Πλήρης Εξόφληση</option>
        </select>
      </div>

      <div id="amountGroup" class="form-group" style="margin-bottom: 14px; display: none;">
        <label style="font-weight: 700; font-size: 0.8rem; margin-bottom: 6px; display: block;">Ποσό Πληρωμής (€)</label>
        <input type="number" step="0.01" id="modalPaidAmount" class="form-control" style="width: 100%; padding: 8px; border-radius: 8px; border: 1px solid var(--gp-card-border); background: var(--gp-card-bg); color: var(--gp-text);">
      </div>

      <div id="dateGroup" class="form-group" style="margin-bottom: 14px; display: none;">
        <label style="font-weight: 700; font-size: 0.8rem; margin-bottom: 6px; display: block;">Ημερομηνία Πληρωμής</label>
        <input type="date" id="modalPaidDate" class="form-control" style="width: 100%; padding: 8px; border-radius: 8px; border: 1px solid var(--gp-card-border); background: var(--gp-card-bg); color: var(--gp-text);">
      </div>

      <div class="form-group" style="margin-bottom: 20px;">
        <label style="font-weight: 700; font-size: 0.8rem; margin-bottom: 6px; display: block;">Σημειώσεις</label>
        <textarea id="modalNotes" rows="2" class="form-control" style="width: 100%; padding: 8px; border-radius: 8px; border: 1px solid var(--gp-card-border); background: var(--gp-card-bg); color: var(--gp-text); font-size: 0.82rem;" placeholder="π.χ. Τράπεζα Πειραιώς, αρ. συναλλαγής..."></textarea>
      </div>

      <div style="display: flex; gap: 8px; justify-content: flex-end;">
        <button type="button" class="btn btn-secondary btn-sm" onclick="closePaymentModal()">Ακύρωση</button>
        <button type="submit" class="btn btn-primary btn-sm">Αποθήκευση</button>
      </div>
    </form>
  </div>
</div>

<script>
let currentAgreed = 0;

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.job-row.clickable').forEach(function(row) {
        row.addEventListener('click', function(e) {
            if (e.target.tagName === 'A' || e.target.closest('a')) {
                return;
            }
            
            const data = {
                id: this.getAttribute('data-payment-id'),
                code: this.getAttribute('data-payment-code'),
                title: this.getAttribute('data-payment-title'),
                agreed: parseFloat(this.getAttribute('data-payment-agreed')) || 0,
                paid: parseFloat(this.getAttribute('data-payment-paid')) || 0,
                date: this.getAttribute('data-payment-date') || new Date().toISOString().split('T')[0],
                status: this.getAttribute('data-payment-status'),
                notes: this.getAttribute('data-payment-notes') || ''
            };
            
            showPaymentModal(data);
        });
    });
});

function showPaymentModal(data) {
    currentAgreed = data.agreed;
    
    document.getElementById('modalPaymentId').value = data.id;
    document.getElementById('modalProjectName').textContent = data.code + ' - ' + data.title;
    document.getElementById('modalAgreedCost').textContent = '€ ' + currentAgreed.toFixed(2);
    document.getElementById('modalNotes').value = data.notes;
    
    const paidAmountInput = document.getElementById('modalPaidAmount');
    const paidDateInput = document.getElementById('modalPaidDate');
    const typeSelect = document.getElementById('modalPaymentType');
    
    if (data.status === 'paid') {
        typeSelect.value = 'full';
        paidAmountInput.value = currentAgreed;
        paidDateInput.value = data.date;
    } else if (data.paid > 0) {
        typeSelect.value = 'partial';
        paidAmountInput.value = data.paid;
        paidDateInput.value = data.date;
    } else {
        typeSelect.value = 'unpaid';
        paidAmountInput.value = '';
        paidDateInput.value = new Date().toISOString().split('T')[0];
    }
    
    handlePaymentTypeChange();
    document.getElementById('paymentModal').classList.add('open');
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.remove('open');
}

function handlePaymentTypeChange() {
    const type = document.getElementById('modalPaymentType').value;
    const amountGroup = document.getElementById('amountGroup');
    const dateGroup = document.getElementById('dateGroup');
    const paidAmountInput = document.getElementById('modalPaidAmount');
    
    if (type === 'unpaid') {
        amountGroup.style.display = 'none';
        dateGroup.style.display = 'none';
    } else if (type === 'partial') {
        amountGroup.style.display = 'block';
        dateGroup.style.display = 'block';
        if (parseFloat(paidAmountInput.value) === currentAgreed) {
            paidAmountInput.value = '';
        }
    } else if (type === 'full') {
        amountGroup.style.display = 'none';
        dateGroup.style.display = 'block';
        paidAmountInput.value = currentAgreed;
    }
}

function submitPaymentForm(e) {
    e.preventDefault();
    
    const id = document.getElementById('modalPaymentId').value;
    const type = document.getElementById('modalPaymentType').value;
    const notes = document.getElementById('modalNotes').value;
    
    let status = 'done';
    let paidAmount = 0;
    
    if (type === 'full') {
        status = 'paid';
        paidAmount = currentAgreed;
    } else if (type === 'partial') {
        status = 'done';
        paidAmount = parseFloat(document.getElementById('modalPaidAmount').value) || 0;
        if (paidAmount <= 0) {
            alert('Παρακαλώ εισάγετε ένα έγκυρο ποσό πληρωμής.');
            return;
        }
        if (paidAmount >= currentAgreed) {
            status = 'paid';
            paidAmount = currentAgreed;
        }
    } else {
        status = 'done';
        paidAmount = 0;
    }
    
    const paidDate = document.getElementById('modalPaidDate').value;
    
    const formData = new URLSearchParams();
    formData.append('id', id);
    formData.append('action', 'save_payment');
    formData.append('status', status);
    formData.append('paid_amount', paidAmount);
    formData.append('paid_date', paidDate);
    formData.append('notes', notes);
    
    fetch('/gopools/public/api/partner_mark_paid.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData.toString()
    })
    .then(response => response.json())
    .then(data => {
        if (data.ok) {
            window.location.reload();
        } else {
            alert('Σφάλμα: ' + (data.error || 'Άγνωστο σφάλμα'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Σφάλμα κατά την αποθήκευση της πληρωμής.');
    });
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
