<?php
// process_doctor_payment.php - Process Doctor Payment
include 'layouts/session.php';
include 'layouts/dbconn.php';

$batch_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get batch details
$batch_sql = "SELECT dpb.*, u.full_name as doctor_name, d.specialization
              FROM doctor_payment_batches dpb
              JOIN doctors d ON dpb.doctor_id = d.doctor_id
              JOIN users u ON d.user_id = u.user_id
              WHERE dpb.batch_id = ? AND dpb.status = 'APPROVED'";
$stmt = $conn->prepare($batch_sql);
$stmt->bind_param('i', $batch_id);
$stmt->execute();
$batch = $stmt->get_result()->fetch_assoc();

if (!$batch) {
    $_SESSION['error_message'] = "Batch not found or cannot be processed";
    header("Location: doctor_payment_batches.php");
    exit();
}

// Handle payment processing
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    
    try {
        $payment_date = $_POST['payment_date'];
        $payment_reference = trim($_POST['payment_reference']);
        $processed_by = $_SESSION['user_id'];
        
        // Update batch
        $update_batch_sql = "UPDATE doctor_payment_batches SET
                            status = 'PAID',
                            payment_date = ?,
                            payment_reference = ?,
                            processed_by = ?,
                            processed_at = CURRENT_TIMESTAMP
                            WHERE batch_id = ?";
        $stmt = $conn->prepare($update_batch_sql);
        $stmt->bind_param('ssii', $payment_date, $payment_reference, $processed_by, $batch_id);
        $stmt->execute();
        
        // Update all allocations in batch to PAID
        $update_alloc_sql = "UPDATE payment_allocations pa
                            JOIN batch_allocation_items bai ON pa.allocation_id = bai.allocation_id
                            SET pa.doctor_payment_status = 'PAID',
                                pa.doctor_payment_date = ?,
                                pa.doctor_payment_reference = ?
                            WHERE bai.batch_id = ?";
        $stmt = $conn->prepare($update_alloc_sql);
        $stmt->bind_param('ssi', $payment_date, $payment_reference, $batch_id);
        $stmt->execute();
        
        // Log activity
        $activity_sql = "INSERT INTO activity_logs (user_id, action, description, ip_address)
                        VALUES (?, 'PROCESS_PAYMENT_BATCH', ?, ?)";
        $stmt = $conn->prepare($activity_sql);
        $description = "Processed payment batch: {$batch['batch_number']} - KES " . number_format($batch['net_payable'], 2);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $stmt->bind_param('iss', $processed_by, $description, $ip_address);
        $stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Payment processed successfully!";
        header("Location: view_payment_batch.php?id=" . $batch_id);
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Payment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="page-header" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); padding: 2rem; border-radius: 12px; color: white; margin-bottom: 2rem;">
                        <h3 class="text-white mb-2"><i class="ri-money-dollar-circle-line me-2"></i>Process Payment</h3>
                        <p class="text-white opacity-75 mb-0">Complete payment for batch: <?php echo htmlspecialchars($batch['batch_number']); ?></p>
                    </div>
                    
                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i><?php echo htmlspecialchars($error_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-lg-8 mx-auto">
                            
                            <!-- Payment Summary -->
                            <div class="card mb-4">
                                <div class="card-body">
                                    <h5 class="card-title mb-4">Payment Summary</h5>
                                    
                                    <div class="table-responsive">
                                        <table class="table">
                                            <tr>
                                                <td><strong>Doctor:</strong></td>
                                                <td class="text-end"><?php echo htmlspecialchars($batch['doctor_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Period:</strong></td>
                                                <td class="text-end">
                                                    <?php echo date('d M', strtotime($batch['payment_period_start'])); ?> - 
                                                    <?php echo date('d M Y', strtotime($batch['payment_period_end'])); ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><strong>Number of Allocations:</strong></td>
                                                <td class="text-end"><?php echo $batch['total_allocations']; ?></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Gross Amount:</strong></td>
                                                <td class="text-end">KES <?php echo number_format($batch['gross_amount'], 2); ?></td>
                                            </tr>
                                            <?php if ($batch['total_tax_withheld'] > 0): ?>
                                            <tr>
                                                <td>Less: Tax Withheld:</td>
                                                <td class="text-end text-danger">KES <?php echo number_format($batch['total_tax_withheld'], 2); ?></td>
                                            </tr>
                                            <?php endif; ?>
                                            <?php if ($batch['total_deductions'] > 0): ?>
                                            <tr>
                                                <td>Less: Other Deductions:</td>
                                                <td class="text-end text-danger">KES <?php echo number_format($batch['total_deductions'], 2); ?></td>
                                            </tr>
                                            <?php endif; ?>
                                            <tr class="table-success">
                                                <td><strong>Net Payable:</strong></td>
                                                <td class="text-end"><strong class="fs-4 text-success">KES <?php echo number_format($batch['net_payable'], 2); ?></strong></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Payment Details Form -->
                            <form method="POST" action="" id="paymentForm">
                                <div class="card mb-4">
                                    <div class="card-body">
                                        <h5 class="card-title mb-4">Payment Details</h5>
                                        
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Payment Date <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control datepicker" name="payment_date" 
                                                       value="<?php echo date('Y-m-d'); ?>" required>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label class="form-label">Payment Method (Read-only)</label>
                                                <input type="text" class="form-control" 
                                                       value="<?php echo str_replace('_', ' ', $batch['payment_method']); ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-12">
                                                <label class="form-label">Payment Reference / Transaction ID <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="payment_reference" 
                                                       placeholder="Enter payment reference or transaction ID" required>
                                                <small class="text-muted">Bank reference, M-Pesa code, or cheque number</small>
                                            </div>
                                            
                                            <?php if ($batch['bank_name']): ?>
                                            <div class="col-md-6">
                                                <label class="form-label">Bank Name (Read-only)</label>
                                                <input type="text" class="form-control" 
                                                       value="<?php echo htmlspecialchars($batch['bank_name']); ?>" readonly>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($batch['account_number']): ?>
                                            <div class="col-md-6">
                                                <label class="form-label">Account Number (Read-only)</label>
                                                <input type="text" class="form-control" 
                                                       value="<?php echo htmlspecialchars($batch['account_number']); ?>" readonly>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($batch['mpesa_number']): ?>
                                            <div class="col-md-6">
                                                <label class="form-label">M-Pesa Number (Read-only)</label>
                                                <input type="text" class="form-control" 
                                                       value="<?php echo htmlspecialchars($batch['mpesa_number']); ?>" readonly>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="alert alert-info mt-4">
                                            <i class="ri-information-line me-2"></i>
                                            <strong>Important:</strong> Once processed, this payment cannot be undone. 
                                            All allocations in this batch will be marked as PAID.
                                        </div>
                                        
                                        <div class="form-check mt-3">
                                            <input class="form-check-input" type="checkbox" id="confirmPayment" required>
                                            <label class="form-check-label" for="confirmPayment">
                                                I confirm that the payment of <strong>KES <?php echo number_format($batch['net_payable'], 2); ?></strong> 
                                                has been successfully transferred to the doctor
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between">
                                            <a href="view_payment_batch.php?id=<?php echo $batch_id; ?>" class="btn btn-secondary">
                                                <i class="ri-close-line me-1"></i>Cancel
                                            </a>
                                            <button type="submit" class="btn btn-success">
                                                <i class="ri-check-double-line me-1"></i>Process Payment
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                            
                        </div>
                    </div>
                    
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        flatpickr('.datepicker', {
            dateFormat: 'Y-m-d',
            maxDate: 'today'
        });
        
        document.getElementById('paymentForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            Swal.fire({
                title: 'Process Payment?',
                html: 'Confirm payment of <strong>KES <?php echo number_format($batch['net_payable'], 2); ?></strong><br>This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#10b981',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Process Payment',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Processing...',
                        text: 'Please wait',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    this.submit();
                }
            });
        });
    </script>
</body>
</html>