<?php
/**
 * Record a fee payment via the express scanner.
 * POST: student_id, fee_structure_id, amount, payment_method, momo_network (optional)
 * Extends existing payment logic — sets recorded_via = 'express_scanner'.
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once '../config.php';
require_once '../includes/canteen_helpers.php';

// ── Auth ──────────────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit;
}
canteen_require_role(['admin', 'headteacher', 'accountant', 'cashier', 'registrar'], true);
canteen_require_active();

// ── Input & validation ────────────────────────────────────────────────────────
$student_id       = (int)   ($_POST['student_id']       ?? 0);
$fee_structure_id = (int)   ($_POST['fee_structure_id'] ?? 0);
$amount           = (float) ($_POST['amount']           ?? 0);
$payment_method   = trim((string) ($_POST['payment_method'] ?? 'cash'));
$momo_network     = trim((string) ($_POST['momo_network']   ?? ''));

if ($student_id <= 0 || $fee_structure_id <= 0 || $amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid payment details.']);
    exit;
}

$allowed_methods = ['cash', 'mobile_money', 'bank_transfer'];
if (!in_array($payment_method, $allowed_methods, true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid payment method.']);
    exit;
}

// Map mobile_money → 'online' for the existing ENUM column
$db_payment_method = ($payment_method === 'mobile_money') ? 'online' : $payment_method;

// Build notes — include MoMo network if provided
$notes = 'Express scanner';
if ($payment_method === 'mobile_money' && $momo_network !== '') {
    $notes = 'Mobile Money (' . $momo_network . ') — Express scanner';
}

$conn = getDBConnection();

// ── Verify student & fee structure exist ──────────────────────────────────────
$s_stmt = $conn->prepare(
    "SELECT s.id, s.first_name, s.last_name, s.class, s.phone,
            fs.fee_type, fs.amount AS structure_amount
     FROM students s
     JOIN fee_structures fs ON fs.id = ?
     WHERE s.id = ? AND s.status = 'active' AND fs.class_name = s.class
     LIMIT 1"
);
$s_stmt->bind_param('ii', $fee_structure_id, $student_id);
$s_stmt->execute();
$row = $s_stmt->get_result()->fetch_assoc();
$s_stmt->close();

if (!$row) {
    echo json_encode(['success' => false, 'message' => 'Student or fee structure not found.']);
    exit;
}

$student_name  = $row['first_name'] . ' ' . $row['last_name'];
$fee_type_name = $row['fee_type'];
$parent_phone  = $row['phone'] ?? '';

// ── INSERT payment (extends existing logic, adds recorded_via) ────────────────
$payment_date = date('Y-m-d');
$recorded_via = 'express_scanner';

$pay_stmt = $conn->prepare(
    "INSERT INTO payments
     (student_id, fee_structure_id, amount_paid, payment_date,
      payment_method, notes, recorded_via)
     VALUES (?, ?, ?, ?, ?, ?, ?)"
);
$pay_stmt->bind_param(
    'iidssss',
    $student_id, $fee_structure_id, $amount,
    $payment_date, $db_payment_method, $notes, $recorded_via
);

if (!$pay_stmt->execute()) {
    $err = $pay_stmt->error;
    $pay_stmt->close();
    echo json_encode(['success' => false, 'message' => 'Payment INSERT failed: ' . $err]);
    exit;
}
$payment_id = (int) $conn->insert_id;
$pay_stmt->close();

// ── Canteen entitlement (feeding fees only — silent on failure) ───────────────
canteen_auto_generate_entitlement($student_id, $payment_id, $fee_type_name);

// ── SMS confirmation ──────────────────────────────────────────────────────────
if (!empty($parent_phone)) {
    $school_name = defined('SITE_NAME') ? SITE_NAME : 'School';
    $amount_fmt  = number_format($amount, 2);
    $sms_text    = "{$school_name}: Payment of GHS {$amount_fmt} recorded for {$student_name} ({$fee_type_name}) on {$payment_date}. Thank you.";
    @sendSMS($parent_phone, $sms_text);
}

// ── Activity log ──────────────────────────────────────────────────────────────
$user_id = (int) $_SESSION['user_id'];
$log_detail = "Express payment: {$student_name} | {$fee_type_name} | GHS {$amount} | {$payment_method}";
logActivity($conn, $user_id, 'express_payment', $log_detail);

echo json_encode([
    'success'      => true,
    'message'      => 'Payment recorded successfully.',
    'payment_id'   => $payment_id,
    'student_name' => $student_name,
    'fee_type'     => $fee_type_name,
    'amount'       => $amount,
    'parent_phone' => !empty($parent_phone) ? substr($parent_phone, 0, 4) . '****' : '',
]);
