<?php
// create_payment_batch.php - Create Payment Batch for Doctor
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Get doctors for selection
$doctors_sql = "SELECT d.doctor_id, u.full_name, d.specialization 
                FROM doctors d 
                JOIN users u ON d.user_id = u.user_id 
                WHERE d.is_active = 1 
                ORDER BY u.full_name";
$doctors = $conn->query($doctors_sql);

// If doctor selected, get approved unpaid allocations
$doctor_id = isset($_GET['doctor_id']) ? intval($_GET['doctor_id']) : 0;
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');

$allocations = null;
if ($doctor_id > 0) {
    $allocations_sql = "SELECT pa.*, esp.provider_name, bp.payment_number
                        FROM payment_allocations pa
                        JOIN bulk_payments bp ON pa.bulk_payment_id = bp.bulk_payment_id
                        JOIN external_service_providers esp ON pa.provider_id = esp.provider_id
                        WHERE pa.doctor_id = ? 
                        AND pa.allocation_status = 'APPROVED'
                        AND pa.doctor_payment_status IN ('PENDING', 'PROCESSED')
                        AND pa.service_date BETWEEN ? AND ?
                        ORDER BY pa.service_date DESC";
    $stmt = $conn->prepare($allocations_sql);
    $stmt->bind_param('iss', $doctor_id, $date_from, $date_to);
    $stmt->execute();
    $allocations = $stmt->get_result();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_batch'])) {
    $conn->begin_transaction();
    
    try {
        $batch_number = 'BATCH-' . date('Y') . '-' . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);
        
        $doctor_id = intval($_POST['doctor_id']);
        $payment_period_start = $_POST['payment_period_start'];
        $payment_period_end = $_POST['payment_period_end'];
        $payment_method = $_POST['payment_method'];
        $bank_name = trim($_POST['bank_name'] ?? '');
        $account_number = trim($_POST['account_number'] ?? '');
        $mpesa_number = trim($_POST['mpesa_number'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        $created_by = $_SESSION['user_id'];
        
        $selected_allocations = $_POST['allocations'] ?? [];
        
        if (empty($selected_allocations)) {
            throw new Exception("Please select at least one allocation");
        }
        
        // Insert batch
        $insert_batch_sql = "INSERT INTO doctor_payment_batches 
                            (batch_number, doctor_id, payment_period_start, payment_period_end,
                             payment_method, bank_name, account_number, mpesa_number, notes, created_by)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($insert_batch_sql);
        $stmt->bind_param('sisssssssi',
            $batch_number, $doctor_id, $payment_period_start, $payment_period_end,
            $payment_method, $bank_name, $account_number, $mpesa_number, $notes, $created_by
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to create batch");
        }
        
        $batch_id = $conn->insert_id;
        
        // Add allocations to batch
        $insert_item_sql = "INSERT INTO batch_allocation_items (batch_id, allocation_id, amount_included)
                           VALUES (?, ?, ?)";
        $stmt = $conn->prepare($insert_item_sql);
        
        foreach ($selected_allocations as $allocation_id) {
            // Get allocation amount
            $get_amount_sql = "SELECT net_doctor_payment FROM payment_allocations WHERE allocation_id = ?";
            $stmt2 = $conn->prepare($get_amount_sql);
            $stmt2->bind_param('i', $allocation_id);
            $stmt2->execute();
            $amount = $stmt2->get_result()->fetch_assoc()['net_doctor_payment'];
            
            $stmt->bind_param('iid', $batch_id, $allocation_id, $amount);
            $stmt->execute();
            
            // Update allocation status
            $update_alloc_sql = "UPDATE payment_allocations 
                                SET doctor_payment_status = 'PROCESSED' 
                                WHERE allocation_id = ?";
            $stmt2 = $conn->prepare($update_alloc_sql);
            $stmt2->bind_param('i', $allocation_id);
            $stmt2->execute();
        }
        
        // Log activity
        $activity_sql = "INSERT INTO activity_logs (user_id, action, description, ip_address)
                        VALUES (?, 'CREATE_PAYMENT_BATCH', ?, ?)";
        $stmt = $conn->prepare($activity_sql);
        $description = "Created payment batch: {$batch_number}";
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $stmt->bind_param('iss', $created_by, $description, $ip_address);
        $stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Payment batch created 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' => 'Create Payment Batch')); ?>
    <?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, #3b82f6 0%, #2563eb 100%); padding: 2rem; border-radius: 12px; color: white; margin-bottom: 2rem;">
                        <h3 class="text-white mb-2"><i class="ri-group-line me-2"></i>Create Payment Batch</h3>
                        <p class="text-white opacity-75 mb-0">Group allocations for batch payment to doctor</p>
                    </div>
                    
                    <!-- Step 1: Select Doctor and Period -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <h5 class="card-title mb-4">Step 1: Select Doctor and Period</h5>
                            
                            <form method="GET" action="">
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Doctor</label>
                                        <select class="form-select" name="doctor_id" required>
                                            <option value="">Select doctor...</option>
                                            <?php 
                                            $doctors->data_seek(0);
                                            while ($doctor = $doctors->fetch_assoc()): 
                                            ?>
                                                <option value="<?php echo $doctor['doctor_id']; ?>" 
                                                        <?php echo $doctor_id == $doctor['doctor_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($doctor['full_name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">From Date</label>
                                        <input type="text" class="form-control datepicker" name="date_from" 
                                               value="<?php echo htmlspecialchars($date_from); ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">To Date</label>
                                        <input type="text" class="form-control datepicker" name="date_to" 
                                               value="<?php echo htmlspecialchars($date_to); ?>">
                                    </div>
                                    <div class="col-md-2 d-flex align-items-end">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-search-line me-1"></i>Load Allocations
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Step 2: Select Allocations -->
                    <?php if ($allocations && $allocations->num_rows > 0): ?>
                    <form method="POST" action="" id="batchForm">
                        <input type="hidden" name="doctor_id" value="<?php echo $doctor_id; ?>">
                        <input type="hidden" name="payment_period_start" value="<?php echo $date_from; ?>">
                        <input type="hidden" name="payment_period_end" value="<?php echo $date_to; ?>">
                        
                        <div class="card mb-4">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h5 class="card-title mb-0">Step 2: Select Allocations (<?php echo $allocations->num_rows; ?>)</h5>
                                    <button type="button" class="btn btn-sm btn-secondary" onclick="toggleAll()">
                                        <i class="ri-checkbox-line me-1"></i>Toggle All
                                    </button>
                                </div>
                                
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th width="50">
                                                    <input type="checkbox" id="selectAll" onchange="toggleAll()">
                                                </th>
                                                <th>Allocation #</th>
                                                <th>Service Date</th>
                                                <th>Provider</th>
                                                <th>Service</th>
                                                <th class="text-end">Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $total_selected = 0;
                                            while ($alloc = $allocations->fetch_assoc()): 
                                            ?>
                                            <tr>
                                                <td>
                                                    <input type="checkbox" name="allocations[]" 
                                                           value="<?php echo $alloc['allocation_id']; ?>"
                                                           class="allocation-checkbox"
                                                           data-amount="<?php echo $alloc['net_doctor_payment']; ?>">
                                                </td>
                                                <td><?php echo htmlspecialchars($alloc['allocation_number']); ?></td>
                                                <td><?php echo date('d M Y', strtotime($alloc['service_date'])); ?></td>
                                                <td><?php echo htmlspecialchars($alloc['provider_name']); ?></td>
                                                <td><?php echo ucfirst(strtolower($alloc['service_category'])); ?></td>
                                                <td class="text-end">KES <?php echo number_format($alloc['net_doctor_payment'], 2); ?></td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr class="table-primary">
                                                <td colspan="5"><strong>Selected Total:</strong></td>
                                                <td class="text-end"><strong id="selectedTotal">KES 0.00</strong></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Step 3: Payment Details -->
                        <div class="card mb-4">
                            <div class="card-body">
                                <h5 class="card-title mb-4">Step 3: Payment Details</h5>
                                
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Payment Method</label>
                                        <select class="form-select" name="payment_method" id="paymentMethod" required>
                                            <option value="BANK_TRANSFER">Bank Transfer</option>
                                            <option value="MOBILE_MONEY">M-Pesa</option>
                                            <option value="CHEQUE">Cheque</option>
                                            <option value="CASH">Cash</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-4" id="bankFields">
                                        <label class="form-label">Bank Name</label>
                                        <input type="text" class="form-control" name="bank_name" placeholder="Bank name">
                                    </div>
                                    
                                    <div class="col-md-4" id="accountFields">
                                        <label class="form-label">Account Number</label>
                                        <input type="text" class="form-control" name="account_number" placeholder="Account number">
                                    </div>
                                    
                                    <div class="col-md-4 d-none" id="mpesaFields">
                                        <label class="form-label">M-Pesa Number</label>
                                        <input type="text" class="form-control" name="mpesa_number" placeholder="+254...">
                                    </div>
                                    
                                    <div class="col-md-12">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="notes" rows="3"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <a href="doctor_payment_batches.php" class="btn btn-secondary">Cancel</a>
                                    <button type="submit" name="create_batch" class="btn btn-success">
                                        <i class="ri-check-line me-1"></i>Create Batch
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                    
                    <?php elseif ($doctor_id > 0): ?>
                    <div class="card">
                        <div class="card-body text-center py-5">
                            <i class="ri-file-list-line display-4 text-muted"></i>
                            <h5 class="mt-3">No Approved Allocations Found</h5>
                            <p class="text-muted">No unpaid allocations for the selected doctor and period</p>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                </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' });
        
        function toggleAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.allocation-checkbox');
            checkboxes.forEach(cb => cb.checked = selectAll.checked);
            updateTotal();
        }
        
        document.querySelectorAll('.allocation-checkbox').forEach(cb => {
            cb.addEventListener('change', updateTotal);
        });
        
        function updateTotal() {
            let total = 0;
            document.querySelectorAll('.allocation-checkbox:checked').forEach(cb => {
                total += parseFloat(cb.dataset.amount);
            });
            document.getElementById('selectedTotal').textContent = 
                'KES ' + total.toLocaleString('en-US', {minimumFractionDigits: 2});
        }
        
        document.getElementById('paymentMethod').addEventListener('change', function() {
            const bankFields = document.getElementById('bankFields');
            const accountFields = document.getElementById('accountFields');
            const mpesaFields = document.getElementById('mpesaFields');
            
            if (this.value === 'MOBILE_MONEY') {
                bankFields.classList.add('d-none');
                accountFields.classList.add('d-none');
                mpesaFields.classList.remove('d-none');
            } else if (this.value === 'BANK_TRANSFER') {
                bankFields.classList.remove('d-none');
                accountFields.classList.remove('d-none');
                mpesaFields.classList.add('d-none');
            } else {
                bankFields.classList.add('d-none');
                accountFields.classList.add('d-none');
                mpesaFields.classList.add('d-none');
            }
        });
    </script>
</body>
</html>