<?php
header('Content-Type: application/json');
require("../../includes/config.php");

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['payments']) || empty($data['payments'])) {
    echo json_encode(['status' => 'error', 'message' => 'No payment data received']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    $receipt_no = "REC-" . time();
    $remarks = $data['remarks'] ?? 'Bulk Payment';
    $payment_mode = $data['payment_mode'] ?? 'Cash';
    
    // --- NEW: Capture Discount Percent from JSON Payload ---
    $discount_percent = floatval($data['discount_percent'] ?? 0);

    foreach ($data['payments'] as $pay) {
        $assign_id = intval($pay['fee_id']);
        $amount_before_discount = floatval($pay['amount']);

        if ($amount_before_discount <= 0) continue; 

        // 1. Fetch current balance
        $stmt = $pdo->prepare("SELECT student_id, fee_type_id, remaining_amount, total_amount 
                               FROM fee_assign WHERE id = ? FOR UPDATE");
        $stmt->execute([$assign_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) throw new Exception("Fee Assignment ID $assign_id not found.");

        $current_balance = floatval($row['remaining_amount']);
        
        if ($amount_before_discount > $current_balance) {
            throw new Exception("Payment exceeds remaining balance for one of the items.");
        }

        // --- NEW: Calculate the Actual Discount for this specific Fee Line ---
        // Formula: Amount - (Amount * Percent / 100)
        $individual_discount_value = ($amount_before_discount * $discount_percent) / 100;
        $actual_cash_received = $amount_before_discount - $individual_discount_value;

        // 2. Insert into fee_payments 
        // Note: We save amount_paid as the discounted cash, but we settle the full amount in fee_assign
        $paySql = "INSERT INTO fee_payments 
                   (fee_assign_id, student_id, fee_type_id, amount_paid, discount_amount, payment_mode, receipt_number, remarks, payment_date) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $pdo->prepare($paySql)->execute([
            $assign_id, 
            $row['student_id'], 
            $row['fee_type_id'], 
            $actual_cash_received,      // Cash actually taken
            $individual_discount_value, // Discount recorded
            $payment_mode, 
            $receipt_no, 
            $remarks
        ]);

        // 3. Update the Assignment Table
        // IMPORTANT: We subtract the FULL amount (Cash + Discount) from the balance
        $new_balance = $current_balance - $amount_before_discount;
        $new_status = ($new_balance <= 0) ? 'paid' : 'partially_paid';
        
        $updSql = "UPDATE fee_assign SET remaining_amount = ?, payment_status = ? WHERE id = ?";
        $pdo->prepare($updSql)->execute([$new_balance, $new_status, $assign_id]);
    }

    $pdo->commit();
    echo json_encode([
        'status' => 'success', 
        'receipt_no' => $receipt_no,
        'message' => 'Payment processed successfully'
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>