<?php
// committee_add_payment.php
require 'db.php';
require 'helpers.php';
require_committee();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: committee_dashboard.php');
    exit;
}

// Verify CSRF token
if (!verify_csrf_token($_POST['csrf'] ?? '')) {
    die('Invalid CSRF token');
}

$student_id = $_POST['student_id'] ?? '';
$fee_type_id = (int)($_POST['fee_type_id'] ?? 0);
$payment_amount = (float)($_POST['payment_amount'] ?? 0);
$payment_reference = $_POST['payment_reference'] ?? '';
$transaction_ref = $_POST['transaction_ref'] ?? '';
$bank_id = !empty($_POST['bank_id']) ? (int)$_POST['bank_id'] : null;
$registration_fees = (float)($_POST['registration_fees'] ?? 0);
$insurance_fees = (float)($_POST['insurance_fees'] ?? 0);
$study_fees = (float)($_POST['study_fees'] ?? 0);
$discount = (float)($_POST['discount'] ?? 0);

if (empty($student_id) || $payment_amount <= 0 || empty($payment_reference)) {
    die('Invalid input data');
}

// Check committee access to this student
$accessCheck = $mysqli1->prepare("SELECT college_id, student_name FROM students WHERE student_id = ?");
$accessCheck->bind_param("s", $student_id);
$accessCheck->execute();
$student = $accessCheck->get_result()->fetch_assoc();

if (!$student) {
    die('Student not found');
}

// Get current semester (you might want to adjust this logic)
$semester_stmt = $mysqli1->query("SELECT id FROM semesters WHERE is_current = 1 LIMIT 1");
$current_semester = $semester_stmt->fetch_assoc();
$semester_id = $current_semester['id'] ?? null;

// Insert payment record into existing payments table
$stmt = $mysqli1->prepare("
    INSERT INTO payments 
    (student_id, student_name, payment_reference, semester_id, payment_amount, 
     transaction_ref, bank_id, fee_type_id, registration_fees, insurance_fees, 
     study_fees, discount, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
");

$stmt->bind_param(
    "sssidssiiddd", 
    $student_id, 
    $student['student_name'],
    $payment_reference, 
    $semester_id,
    $payment_amount, 
    $transaction_ref, 
    $bank_id, 
    $fee_type_id, 
    $registration_fees, 
    $insurance_fees, 
    $study_fees, 
    $discount
);

if ($stmt->execute()) {
    header('Location: committee_student_profile.php?student_id=' . urlencode($student_id) . '&success=1');
} else {
    die('Error saving payment: ' . $mysqli1->error);
}