<?php
session_start();

// If coming from previous form, store data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $_SESSION['budget_data'] = $_POST;
    
    // Calculate totals
    $_SESSION['remaining_budget'] = ($_POST['govt_budget'] ?? 0) - ($_POST['budget_expenses'] ?? 0);
    $_SESSION['remaining_fee'] = ($_POST['fee_collected'] ?? 0) - ($_POST['fee_expenses'] ?? 0) - ($_POST['submitted_govt'] ?? 0);
    
    header("Location: next_page.php"); // Update with your next page
    exit;
}

// Load previous data if exists
$budget_data = $_SESSION['budget_data'] ?? [];
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>School Budget Report</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: #f5f7fa;
      padding: 15px;
      color: #333;
    }

    .budget-container {
      max-width: 1000px;
      margin: 0 auto;
    }

    .header {
      text-align: center;
      margin-bottom: 20px;
      padding: 15px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .header h1 {
      color: #2c3e50;
      font-size: 22px;
      margin-bottom: 5px;
    }

    .budget-wrapper {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      margin-bottom: 20px;
    }

    @media (max-width: 768px) {
      .budget-wrapper {
        grid-template-columns: 1fr;
      }
    }

    .budget-section {
      background: white;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      border-top: 3px solid;
    }

    .budget-section.govt {
      border-color: #3498db;
    }

    .budget-section.fee {
      border-color: #27ae60;
    }

    .section-title {
      font-size: 16px;
      color: #2c3e50;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .section-title i {
      font-size: 18px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    .form-group label {
      display: block;
      margin-bottom: 5px;
      font-weight: 600;
      color: #444;
      font-size: 13px;
    }

    .input-wrapper {
      position: relative;
    }

    .currency-symbol {
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      color: #666;
      font-size: 14px;
    }

    .budget-input {
      width: 100%;
      padding: 8px 8px 8px 30px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      background: #fafafa;
    }

    .budget-input:focus {
      outline: none;
      border-color: #3498db;
      background: white;
    }

    .budget-input[readonly] {
      background: #f8f9fa;
      font-weight: 600;
    }

    .budget-input.remaining {
      font-size: 14px;
      font-weight: 600;
    }

    .remaining-positive {
      border-color: #27ae60;
      background: #f0f9f0;
      color: #27ae60;
    }

    .remaining-negative {
      border-color: #e74c3c;
      background: #fee;
      color: #e74c3c;
    }

    .remaining-zero {
      border-color: #f39c12;
      background: #fff8e1;
      color: #f39c12;
    }

    .helper-text {
      font-size: 11px;
      color: #777;
      margin-top: 3px;
      display: block;
    }

    .summary-section {
      background: white;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      margin-bottom: 20px;
      border-top: 3px solid #9b59b6;
    }

    .summary-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 15px;
      margin-top: 15px;
    }

    .summary-item {
      padding: 15px;
      background: #f8f9fa;
      border-radius: 6px;
      border-left: 3px solid;
    }

    .summary-item.bank {
      border-color: #3498db;
    }

    .summary-item.school {
      border-color: #e74c3c;
    }

    .summary-item h4 {
      color: #2c3e50;
      font-size: 14px;
      margin-bottom: 10px;
    }

    .summary-item .amount-display {
      font-size: 18px;
      font-weight: 700;
      color: #2c3e50;
    }

    .amount-display.positive {
      color: #27ae60;
    }

    .amount-display.negative {
      color: #e74c3c;
    }

    .submit-btn {
      display: block;
      width: 200px;
      margin: 20px auto;
      padding: 10px 20px;
      background: #2c3e50;
      color: white;
      border: none;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: background 0.3s;
    }

    .submit-btn:hover {
      background: #34495e;
    }

    .submit-btn:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }

    .calculation-note {
      background: #f8f9fa;
      padding: 8px;
      margin-top: 8px;
      border-radius: 4px;
      font-size: 11px;
      color: #666;
    }

    .row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
    }

    @media (max-width: 480px) {
      .row {
        grid-template-columns: 1fr;
      }
      
      .summary-grid {
        grid-template-columns: 1fr;
      }
    }

    .total-box {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 6px;
      margin-top: 15px;
      text-align: center;
    }

    .total-box h4 {
      color: #2c3e50;
      font-size: 14px;
      margin-bottom: 8px;
    }

    .total-amount {
      font-size: 20px;
      font-weight: 700;
      color: #2c3e50;
    }

    .total-amount.positive {
      color: #27ae60;
    }

    .total-amount.negative {
      color: #e74c3c;
    }
    
    .section-divider {
      margin: 20px 0;
      border-top: 1px dashed #ddd;
      padding-top: 20px;
    }
    
    .cash-section {
      background: #f0f9ff;
      padding: 15px;
      border-radius: 6px;
      margin-top: 15px;
      border: 1px solid #3498db;
    }
    
    .cash-section h4 {
      color: #2c3e50;
      font-size: 14px;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  </style>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>

<div class="budget-container">
  <div class="header">
    <h1><i class="fas fa-chart-pie"></i> School Budget Report</h1>
    <p style="font-size: 12px;">Financial Year: <?php echo date('Y'); ?>-<?php echo date('Y') + 1; ?></p>
  </div>

  <form method="POST" action="" id="budgetForm">
    <div class="budget-wrapper">
      <!-- Left: Government Budget -->
      <div class="budget-section govt">
        <h2 class="section-title">
          <i class="fas fa-university"></i> Government Budget
        </h2>
        
        <div class="row">
          <div class="form-group">
            <label for="govt_budget">Budget Allocated</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="govt_budget" name="govt_budget" class="budget-input" 
                     min="0" value="<?php echo $budget_data['govt_budget'] ?? ''; ?>">
            </div>
          </div>

          <div class="form-group">
            <label for="budget_expenses">Expenses</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="budget_expenses" name="budget_expenses" class="budget-input" 
                     min="0" value="<?php echo $budget_data['budget_expenses'] ?? ''; ?>">
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>Remaining Budget</label>
          <div class="input-wrapper">
            <span class="currency-symbol">Rs.</span>
            <input type="text" id="remaining_budget" class="budget-input remaining" readonly>
          </div>
          <div class="calculation-note">
            <strong>Calculation:</strong> Budget Allocated - Expenses
          </div>
        </div>

        <div class="total-box">
          <h4>Government Balance</h4>
          <div id="govtRemainingDisplay" class="total-amount">Rs. 0</div>
        </div>
      </div>

      <!-- Right: School Income -->
      <div class="budget-section fee">
        <h2 class="section-title">
          <i class="fas fa-money-bill-wave"></i> School Income
        </h2>
        
        <!-- Previous Balance Section -->
        <div class="section-divider">
          <div class="form-group">
            <label for="previous_balance">Previous Balance (Carry Forward)</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="previous_balance" name="previous_balance" class="budget-input" 
                     min="0" value="<?php echo $budget_data['previous_balance'] ?? ''; ?>"
                     placeholder="Balance from previous period">
            </div>
          </div>
        </div>
        
        <div class="row">
          <div class="form-group">
            <label for="fee_collected">Fee Collected</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="fee_collected" name="fee_collected" class="budget-input" 
                     min="0" value="<?php echo $budget_data['fee_collected'] ?? ''; ?>">
            </div>
          </div>

          <div class="form-group">
            <label for="donations">Donations</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="donations" name="donations" class="budget-input" 
                     min="0" value="<?php echo $budget_data['donations'] ?? ''; ?>">
            </div>
          </div>
        </div>

        <div class="row">
          <div class="form-group">
            <label for="scout_fund">Scout/Girl Guide Fund</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="scout_fund" name="scout_fund" class="budget-input" 
                     min="0" value="<?php echo $budget_data['scout_fund'] ?? ''; ?>">
            </div>
          </div>

          <div class="form-group">
            <label for="other_income">Other Income</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="other_income" name="other_income" class="budget-input" 
                     min="0" value="<?php echo $budget_data['other_income'] ?? ''; ?>">
            </div>
          </div>
        </div>

        <!-- Cash Position within School Income -->
        <div class="cash-section">
          <h4><i class="fas fa-money-bill-alt"></i> Current Cash Position</h4>
          
          <div class="row">
            <div class="form-group">
              <label for="cash_in_hand">Cash in Hand</label>
              <div class="input-wrapper">
                <span class="currency-symbol">Rs.</span>
                <input type="number" id="cash_in_hand" name="cash_in_hand" class="budget-input" 
                       min="0" value="<?php echo $budget_data['cash_in_hand'] ?? ''; ?>"
                       placeholder="Petty cash available">
              </div>
              <div class="helper-text">Physical cash available at school</div>
            </div>

            <div class="form-group">
              <label for="cash_in_bank">Cash in Bank</label>
              <div class="input-wrapper">
                <span class="currency-symbol">Rs.</span>
                <input type="number" id="cash_in_bank" name="cash_in_bank" class="budget-input" 
                       min="0" value="<?php echo $budget_data['cash_in_bank'] ?? ''; ?>"
                       placeholder="Bank balance">
              </div>
              <div class="helper-text">Amount in school's bank account</div>
            </div>
          </div>
          
          <div class="form-group">
            <label>Total Cash Available</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="text" id="total_cash" class="budget-input" readonly>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>Total Collection (Including Previous Balance)</label>
          <div class="input-wrapper">
            <span class="currency-symbol">Rs.</span>
            <input type="text" id="total_collection" class="budget-input" readonly>
          </div>
          <div class="helper-text">Previous Balance + All Income Sources</div>
        </div>

        <div class="row">
          <div class="form-group">
            <label for="fee_expenses">School Expenses</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="fee_expenses" name="fee_expenses" class="budget-input" 
                     min="0" value="<?php echo $budget_data['fee_expenses'] ?? ''; ?>">
            </div>
          </div>

          <div class="form-group">
            <label for="submitted_govt">Submitted to Govt.</label>
            <div class="input-wrapper">
              <span class="currency-symbol">Rs.</span>
              <input type="number" id="submitted_govt" name="submitted_govt" class="budget-input" 
                     min="0" value="<?php echo $budget_data['submitted_govt'] ?? ''; ?>">
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>Net Balance</label>
          <div class="input-wrapper">
            <span class="currency-symbol">Rs.</span>
            <input type="text" id="remaining_fee" class="budget-input remaining" readonly>
          </div>
          <div class="calculation-note">
            <strong>Calculation:</strong> (Previous Balance + Total Collection) - Expenses - Submitted to Govt.
          </div>
        </div>

        <div class="total-box">
          <h4>School Balance</h4>
          <div id="feeRemainingDisplay" class="total-amount">Rs. 0</div>
        </div>
      </div>
    </div>

    <!-- Summary Section -->
    <div class="summary-section">
      <h2 class="section-title">
        <i class="fas fa-chart-line"></i> Financial Summary
      </h2>
      
      <div class="summary-grid">
        <div class="summary-item bank">
          <h4><i class="fas fa-university"></i> Total Available Funds</h4>
          <div class="amount-display positive" id="totalFunds">Rs. 0</div>
          <div class="helper-text">Government + School Balance</div>
        </div>

        <div class="summary-item school">
          <h4><i class="fas fa-percentage"></i> Fund Utilization</h4>
          <div class="amount-display" id="utilizationRate">0%</div>
          <div class="helper-text">Total Expenses vs Total Budget</div>
        </div>

        <div class="summary-item bank">
          <h4><i class="fas fa-hand-holding-usd"></i> Cash Position</h4>
          <div class="amount-display" id="totalCashPosition">Rs. 0</div>
          <div class="helper-text">Cash in Hand + Cash in Bank</div>
        </div>

        <div class="summary-item school">
          <h4><i class="fas fa-balance-scale"></i> Current Balance</h4>
          <div class="amount-display positive" id="currentBalance">Rs. 0</div>
          <div class="helper-text">Net School Balance</div>
        </div>
      </div>
    </div>

    <button type="submit" class="submit-btn" id="submitBtn">
      <i class="fas fa-save"></i> Save Report
    </button>
  </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const form = document.getElementById('budgetForm');
  const inputs = document.querySelectorAll('input[type="number"]');
  const remainingBudget = document.getElementById('remaining_budget');
  const remainingFee = document.getElementById('remaining_fee');
  const totalCollection = document.getElementById('total_collection');
  const totalCash = document.getElementById('total_cash');
  const govtRemainingDisplay = document.getElementById('govtRemainingDisplay');
  const feeRemainingDisplay = document.getElementById('feeRemainingDisplay');
  const totalFunds = document.getElementById('totalFunds');
  const utilizationRate = document.getElementById('utilizationRate');
  const totalCashPosition = document.getElementById('totalCashPosition');
  const currentBalance = document.getElementById('currentBalance');

  // Format currency in Pakistani Rupees
  function formatCurrency(amount) {
    return 'Rs. ' + amount.toLocaleString('en-PK', {
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    });
  }

  // Calculate all totals
  function calculateAll() {
    // Government calculations
    const govtBudget = parseFloat(document.getElementById('govt_budget').value) || 0;
    const budgetExpenses = parseFloat(document.getElementById('budget_expenses').value) || 0;
    const remainingGovt = govtBudget - budgetExpenses;
    
    // Previous balance
    const previousBalance = parseFloat(document.getElementById('previous_balance').value) || 0;
    
    // School income calculations
    const feeCollected = parseFloat(document.getElementById('fee_collected').value) || 0;
    const donations = parseFloat(document.getElementById('donations').value) || 0;
    const scoutFund = parseFloat(document.getElementById('scout_fund').value) || 0;
    const otherIncome = parseFloat(document.getElementById('other_income').value) || 0;
    
    // Cash positions
    const cashInHand = parseFloat(document.getElementById('cash_in_hand').value) || 0;
    const cashInBank = parseFloat(document.getElementById('cash_in_bank').value) || 0;
    const totalCashAmount = cashInHand + cashInBank;
    
    // Total school collection (including previous balance)
    const totalIncome = feeCollected + donations + scoutFund + otherIncome;
    const totalCollectionAmount = previousBalance + totalIncome;
    
    // School expenses and government submission
    const feeExpenses = parseFloat(document.getElementById('fee_expenses').value) || 0;
    const submittedGovt = parseFloat(document.getElementById('submitted_govt').value) || 0;
    
    // Net school balance
    const remainingFeeAmount = totalCollectionAmount - feeExpenses - submittedGovt;
    
    // Financial summary calculations
    const totalAvailableFunds = remainingGovt + remainingFeeAmount;
    const totalExpenses = budgetExpenses + feeExpenses + submittedGovt;
    const totalBudget = govtBudget + totalCollectionAmount;
    const utilization = totalBudget > 0 ? Math.round((totalExpenses / totalBudget * 100)) : 0;
    
    // Update displays
    remainingBudget.value = formatCurrency(remainingGovt);
    remainingFee.value = formatCurrency(remainingFeeAmount);
    totalCollection.value = formatCurrency(totalCollectionAmount);
    totalCash.value = formatCurrency(totalCashAmount);
    
    govtRemainingDisplay.textContent = formatCurrency(remainingGovt);
    feeRemainingDisplay.textContent = formatCurrency(remainingFeeAmount);
    
    totalFunds.textContent = formatCurrency(totalAvailableFunds);
    totalCashPosition.textContent = formatCurrency(totalCashAmount);
    currentBalance.textContent = formatCurrency(remainingFeeAmount);
    utilizationRate.textContent = utilization + '%';
    
    // Style amounts
    styleRemainingAmount(remainingBudget, remainingGovt);
    styleRemainingAmount(remainingFee, remainingFeeAmount);
    styleAmount(govtRemainingDisplay, remainingGovt);
    styleAmount(feeRemainingDisplay, remainingFeeAmount);
    styleAmount(totalFunds, totalAvailableFunds);
    styleAmount(currentBalance, remainingFeeAmount);
    
    // Style utilization rate
    if (utilization > 80) {
      utilizationRate.classList.remove('positive');
      utilizationRate.classList.add('negative');
    } else {
      utilizationRate.classList.remove('negative');
      utilizationRate.classList.add('positive');
    }
    
    return {
      remainingGovt,
      remainingFeeAmount,
      totalAvailableFunds,
      utilization,
      totalCashAmount
    };
  }

  // Style amount based on value
  function styleAmount(element, amount) {
    element.classList.remove('positive', 'negative');
    
    if (amount > 0) {
      element.classList.add('positive');
    } else if (amount < 0) {
      element.classList.add('negative');
    }
  }

  // Style remaining input
  function styleRemainingInput(element, amount) {
    element.classList.remove('remaining-positive', 'remaining-negative', 'remaining-zero');
    
    if (amount > 0) {
      element.classList.add('remaining-positive');
    } else if (amount < 0) {
      element.classList.add('remaining-negative');
    } else {
      element.classList.add('remaining-zero');
    }
  }

  // Real-time calculation
  inputs.forEach(input => {
    input.addEventListener('input', function() {
      // Validate
      const value = parseFloat(this.value) || 0;
      if (value < 0) {
        this.value = 0;
      }
      
      // Calculate all totals
      calculateAll();
    });
  });

  // Form submission
  form.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const totals = calculateAll();
    
    const summary = `
Budget Report Summary:
----------------------
Previous Balance: ${formatCurrency(parseFloat(document.getElementById('previous_balance').value) || 0)}
Government Balance: ${govtRemainingDisplay.textContent}
School Balance: ${feeRemainingDisplay.textContent}
Cash in Hand: ${formatCurrency(parseFloat(document.getElementById('cash_in_hand').value) || 0)}
Cash in Bank: ${formatCurrency(parseFloat(document.getElementById('cash_in_bank').value) || 0)}
Total Funds Available: ${totalFunds.textContent}
Fund Utilization: ${utilizationRate.textContent}

Save this report?
    `;
    
    if (confirm(summary)) {
      form.submit();
    }
  });

  // Helper function for remaining amounts
  function styleRemainingAmount(element, amount) {
    if (amount > 0) {
      element.classList.remove('remaining-negative', 'remaining-zero');
      element.classList.add('remaining-positive');
    } else if (amount < 0) {
      element.classList.remove('remaining-positive', 'remaining-zero');
      element.classList.add('remaining-negative');
    } else {
      element.classList.remove('remaining-positive', 'remaining-negative');
      element.classList.add('remaining-zero');
    }
  }

  // Initialize on page load
  calculateAll();
});
</script>

</body>
</html>