<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
require_once __DIR__ . '/../includes/require_auth.php';
require_role(['admin', 'accountant', 'cashier']);

header('Content-Type: application/json');
require_once '../config.php';
require_once '../includes/canteen_helpers.php';

$action = $_GET['action'] ?? '';

try {
    $conn = getDBConnection();
    
    if (!$conn) {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        exit;
    }
    
    if ($action === 'add_structure') {
        $class_name    = trim((string) ($_POST['class_name']    ?? ''));
        $fee_type      = trim((string) ($_POST['fee_type']      ?? ''));
        $amount        = floatval($_POST['amount'] ?? 0);
        $due_date      = trim((string) ($_POST['due_date']      ?? ''));
        $academic_year = trim((string) ($_POST['academic_year'] ?? getAcademicYear()));

        if (empty($class_name) || empty($fee_type) || $amount <= 0) {
            echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);
            exit;
        }

        $stmt = $conn->prepare("INSERT INTO fee_structures (class_name, fee_type, amount, due_date, academic_year) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("ssdss", $class_name, $fee_type, $amount, $due_date, $academic_year);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Fee structure added successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to add fee structure: ' . $stmt->error]);
        }
        $stmt->close();
    }
    elseif ($action === 'add_payment') {
        $student_id = intval($_POST['student_id'] ?? 0);
        $fee_structure_id = intval($_POST['fee_structure_id'] ?? 0);
        $amount_paid = floatval($_POST['amount_paid'] ?? 0);
        $payment_date   = trim((string) ($_POST['payment_date']   ?? date('Y-m-d')));
        $payment_method = trim((string) ($_POST['payment_method'] ?? 'cash'));
        $transaction_id = trim((string) ($_POST['transaction_id'] ?? ''));
        $notes          = trim((string) ($_POST['notes']          ?? ''));

        if ($student_id <= 0 || $fee_structure_id <= 0 || $amount_paid <= 0) {
            echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);
            exit;
        }

        $stmt = $conn->prepare("INSERT INTO payments (student_id, fee_structure_id, amount_paid, payment_date, payment_method, transaction_id, notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("iidssss", $student_id, $fee_structure_id, $amount_paid, $payment_date, $payment_method, $transaction_id, $notes);

        if ($stmt->execute()) {
            $payment_id = (int) $conn->insert_id;
            // Canteen Module — auto-generate entitlement for feeding fees
            $ft_stmt = $conn->prepare("SELECT fee_type FROM fee_structures WHERE id = ? LIMIT 1");
            $ft_stmt->bind_param('i', $fee_structure_id);
            $ft_stmt->execute();
            $ft_row = $ft_stmt->get_result()->fetch_assoc();
            $ft_stmt->close();
            if ($ft_row) {
                canteen_auto_generate_entitlement($student_id, $payment_id, $ft_row['fee_type']);
            }
            echo json_encode(['success' => true, 'message' => 'Payment recorded successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to record payment: ' . $stmt->error]);
        }
        $stmt->close();
    }
    elseif ($action === 'delete_structure') {
        $id = intval($_GET['id'] ?? 0);
        
        // First check if there are any payments linked to this fee structure
        $checkStmt = $conn->prepare("SELECT COUNT(*) as count FROM payments WHERE fee_structure_id = ?");
        $checkStmt->bind_param("i", $id);
        $checkStmt->execute();
        $result = $checkStmt->get_result();
        $row = $result->fetch_assoc();
        $checkStmt->close();
        
        if ($row['count'] > 0) {
            echo json_encode(['success' => false, 'message' => 'Cannot delete fee structure. There are payments linked to it.']);
            $conn->close();
            exit;
        }
        
        // No payments, safe to delete
        $stmt = $conn->prepare("DELETE FROM fee_structures WHERE id = ?");
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Fee structure deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete fee structure: ' . $stmt->error]);
        }
        $stmt->close();
    }
    else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    
    $conn->close();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>