<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$response = ['success' => false, 'message' => ''];

try {
    // Get form data
    $appointment_id = isset($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : 0;
    $patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;
    $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
    $payment_method = isset($_POST['payment_method']) ? trim($_POST['payment_method']) : '';
    $payment_reference = isset($_POST['payment_reference']) ? trim($_POST['payment_reference']) : null;
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : null;
    
    // Mobile Money specific fields
    $mpesa_account_number = isset($_POST['mpesa_account_number']) ? trim($_POST['mpesa_account_number']) : null;
    $transaction_id = isset($_POST['transaction_id']) ? trim($_POST['transaction_id']) : null;
    
    // Card specific fields
    $card_last_four = isset($_POST['card_last_four']) ? trim($_POST['card_last_four']) : null;
    
    // Validate required fields
    if (!$appointment_id || !$patient_id || $amount <= 0 || !$payment_method) {
        throw new Exception('All required fields must be filled');
    }
    
    // Valid payment methods according to schema
    $valid_methods = ['CASH', 'CARD', 'MOBILE_MONEY', 'BANK_TRANSFER', 'CHEQUE', 'INSURANCE_DIRECT', 'CORPORATE'];
    if (!in_array($payment_method, $valid_methods)) {
        throw new Exception('Invalid payment method');
    }
    
    // Check permissions
    $allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST'];
    if (!in_array($_SESSION['role_code'], $allowed_roles)) {
        throw new Exception('You do not have permission to process payments');
    }
    
    // Check if payment already exists for this appointment
    $check_sql = "SELECT payment_id FROM payments WHERE visit_id = ? LIMIT 1";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("i", $appointment_id);
    $stmt->execute();
    $existing = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if ($existing) {
        throw new Exception('Payment already recorded for this appointment');
    }
    
    $conn->begin_transaction();
    
    // Generate payment number
    $payment_number = 'PAY' . date('Ymd') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
    
    // Insert payment - ALIGNED WITH SCHEMA
    $sql = "INSERT INTO payments 
            (payment_number, patient_id, visit_id, payment_method, payment_reference,
             amount, currency, mpesa_account_number, card_last_four, transaction_id,
             payment_date, received_by, status, notes, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, 'KES', ?, ?, ?, NOW(), ?, 'COMPLETED', ?, NOW(), NOW())";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . $conn->error);
    }
    
    $stmt->bind_param("siissdsssis", 
        $payment_number,
        $patient_id,
        $appointment_id,  // visit_id field
        $payment_method,
        $payment_reference,
        $amount,
        $mpesa_account_number,
        $card_last_four,
        $transaction_id,
        $_SESSION['user_id'],
        $notes
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to record payment: ' . $stmt->error);
    }
    
    $payment_id = $conn->insert_id;
    $stmt->close();
    
    // Log activity
    $activity_sql = "INSERT INTO activity_logs 
                     (user_id, action_type, entity_type, entity_id, description, ip_address, created_at)
                     VALUES (?, 'CREATE', 'PAYMENT', ?, ?, ?, NOW())";
    
    $description = "Recorded payment of KES " . number_format($amount, 2) . " for appointment ID {$appointment_id} via {$payment_method}";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    
    $stmt = $conn->prepare($activity_sql);
    if ($stmt) {
        $stmt->bind_param("iiss", $_SESSION['user_id'], $payment_id, $description, $ip_address);
        $stmt->execute();
        $stmt->close();
    }
    
    // TODO: Send payment confirmation SMS/Email
    // You can implement this using Africastalking and PHPMailer
    
    $conn->commit();
    
    $response = [
        'success' => true,
        'message' => 'Payment recorded successfully',
        'payment_id' => $payment_id,
        'payment_number' => $payment_number
    ];
    
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollback();
    }
    error_log("Record payment error: " . $e->getMessage());
    $response = [
        'success' => false,
        'message' => $e->getMessage()
    ];
}

if (isset($conn)) {
    $conn->close();
}

echo json_encode($response);
exit();
?>