<?php
// save_financial_contribution.html

// Include the database connection
require_once 'db_connect.php';

// Hardcoded user ID since session is not used
$loggedInUserId = 1;

// --- Fetch necessary data for form dropdowns ---
// Fetch all partners
$partners = [];
$sql_partners = "SELECT partner_id, partner_name, partner_code, phone_number1 
                 FROM Partners 
                 ORDER BY partner_name";
$result_partners = $conn->query($sql_partners);
if ($result_partners && $result_partners->num_rows > 0) {
    while ($row = $result_partners->fetch_assoc()) {
        $partners[] = $row;
    }
}

// Fetch all partnership agreements
$agreements = [];
$sql_agreements = "SELECT agreement_id, agreement_code, partner_id, commitment_amount 
                   FROM Partnership_Agreements 
                   ORDER BY agreement_code";
$result_agreements = $conn->query($sql_agreements);
if ($result_agreements && $result_agreements->num_rows > 0) {
    while ($row = $result_agreements->fetch_assoc()) {
        $agreements[] = $row;
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Record Partnership Contribution</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background-color: #f8f9fa; }
    .container { margin-top: 30px; margin-bottom: 30px; background-color: #ffffff; padding: 30px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); max-width: 700px; }
    h2 { color: #343a40; margin-bottom: 20px; }
    .form-label { font-weight: bold; }
    #partner_autocomplete_list { position: absolute; z-index: 1000; width: 100%; max-height: 200px; overflow-y: auto; border: 1px solid #ccc; border-top: none; background: #fff; }
    #partner_autocomplete_list div { padding: 10px; cursor: pointer; }
    #partner_autocomplete_list div:hover { background: #e9ecef; }
  </style>
</head>
<body>
<div class="container">
  <div class="d-flex justify-content-start mb-3">
    <a href="partners_view_general_Contribution_details.php" class="btn btn-secondary">← Back</a>
  </div>

  <h2 class="text-center">Record Partnership Contribution</h2>

  <form method="POST" action="save_financial_contribution.php">
    <!-- Partner Autocomplete -->
    <div class="mb-3 position-relative">
      <label for="partner_search_input" class="form-label">Partner</label>
      <input type="text" class="form-control" id="partner_search_input" placeholder="Search by Name or Code" autocomplete="off">
      <div id="partner_autocomplete_list"></div>
      <input type="hidden" id="partner_id" name="partner_id" required>
    </div>

    <!-- Agreement Dropdown -->
    <div class="mb-3">
      <label for="agreement_id" class="form-label">Partnership Agreement</label>
      <select class="form-select" id="agreement_id" name="agreement_id" required>
        <option value="">Select Agreement</option>
        <?php foreach ($agreements as $agreement): ?>
          <option value="<?php echo $agreement['agreement_id']; ?>" data-partner-id="<?php echo $agreement['partner_id']; ?>">
            <?php echo htmlspecialchars($agreement['agreement_code']) . " (Commitment: " . number_format($agreement['commitment_amount'], 2) . " TZS)"; ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>

    <!-- Amount and Date -->
    <div class="row mb-3">
      <div class="col-md-6">
        <label for="amount" class="form-label">Amount (TZS)</label>
        <input type="number" step="0.01" class="form-control" id="amount" name="amount" required>
      </div>
      <div class="col-md-6">
        <label for="contribution_date" class="form-label">Contribution Date</label>
        <input type="date" class="form-control" id="contribution_date" name="contribution_date" value="<?php echo date('Y-m-d'); ?>" required>
      </div>
    </div>

    <div class="d-grid">
      <button type="submit" class="btn btn-primary">Record Contribution</button>
    </div>
  </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const partnerSearchInput = document.getElementById('partner_search_input');
  const partnerIdInput = document.getElementById('partner_id');
  const autocompleteList = document.getElementById('partner_autocomplete_list');
  const agreementSelect = document.getElementById('agreement_id');

  const partners = <?php echo json_encode($partners); ?>;
  const agreements = <?php echo json_encode($agreements); ?>;

  function filterPartners(query) {
    autocompleteList.innerHTML = '';
    if (!query) {
      autocompleteList.style.display = 'none';
      return;
    }
    const filteredPartners = partners.filter(p =>
      p.partner_name.toLowerCase().includes(query.toLowerCase()) ||
      p.partner_code.toLowerCase().includes(query.toLowerCase())
    );

    if (filteredPartners.length > 0) {
      filteredPartners.forEach(p => {
        const div = document.createElement('div');
        div.innerHTML = `<strong>${p.partner_name}</strong> (${p.partner_code})`;
        div.addEventListener('click', function() {
          partnerSearchInput.value = `${p.partner_name} (${p.partner_code})`;
          partnerIdInput.value = p.partner_id;
          autocompleteList.style.display = 'none';
          filterAgreements(p.partner_id);
        });
        autocompleteList.appendChild(div);
      });
      autocompleteList.style.display = 'block';
    } else {
      autocompleteList.style.display = 'none';
    }
  }

  function filterAgreements(selectedPartnerId) {
    agreementSelect.innerHTML = '<option value="">Select Agreement</option>';
    const filtered = agreements.filter(a => a.partner_id == selectedPartnerId);
    filtered.forEach(a => {
      const option = document.createElement('option');
      option.value = a.agreement_id;
      option.textContent = `${a.agreement_code} (Commitment: ${Number(a.commitment_amount).toLocaleString('en-US', {minimumFractionDigits: 2})} TZS)`;
      option.dataset.partnerId = a.partner_id;
      agreementSelect.appendChild(option);
    });
    agreementSelect.value = "";
  }

  partnerSearchInput.addEventListener('input', function() {
    const query = this.value;
    if (!query) {
      partnerIdInput.value = '';
      filterAgreements(null);
    }
    filterPartners(query);
  });

  document.addEventListener('click', function(e) {
    if (!partnerSearchInput.contains(e.target) && !autocompleteList.contains(e.target)) {
      autocompleteList.style.display = 'none';
    }
  });

  autocompleteList.style.display = 'none';
});
</script>
</body>
</html>
