<?php
// provider_statement.php - Provider Statement of Account
include 'layouts/session.php';
include 'layouts/dbconn.php';

$provider_id = isset($_GET['id']) ? intval($_GET['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');

// Get provider details
$provider_sql = "SELECT * FROM external_service_providers WHERE provider_id = ?";
$stmt = $conn->prepare($provider_sql);
$stmt->bind_param('i', $provider_id);
$stmt->execute();
$provider = $stmt->get_result()->fetch_assoc();

if (!$provider) {
    $_SESSION['error_message'] = "Provider not found";
    header("Location: list_external_providers.php");
    exit();
}

// Get statement summary
$summary_sql = "SELECT 
    COUNT(DISTINCT bp.bulk_payment_id) as payment_count,
    SUM(bp.total_amount) as total_received,
    COUNT(pa.allocation_id) as allocation_count,
    SUM(pa.total_service_cost) as total_services,
    SUM(pa.doctor_allocation) as total_doctor_share,
    SUM(pa.facility_allocation) as total_facility_share
FROM bulk_payments bp
LEFT JOIN payment_allocations pa ON bp.bulk_payment_id = pa.bulk_payment_id
    AND pa.allocation_status NOT IN ('CANCELLED', 'REJECTED')
WHERE bp.provider_id = ? AND bp.payment_date BETWEEN ? AND ?";

$stmt = $conn->prepare($summary_sql);
$stmt->bind_param('iss', $provider_id, $date_from, $date_to);
$stmt->execute();
$summary = $stmt->get_result()->fetch_assoc();

// Get bulk payments
$payments_sql = "SELECT bp.*, u.full_name as received_by_name
                 FROM bulk_payments bp
                 JOIN users u ON bp.received_by = u.user_id
                 WHERE bp.provider_id = ? AND bp.payment_date BETWEEN ? AND ?
                 ORDER BY bp.payment_date DESC";
$stmt = $conn->prepare($payments_sql);
$stmt->bind_param('iss', $provider_id, $date_from, $date_to);
$stmt->execute();
$payments = $stmt->get_result();

// Get allocations
$allocations_sql = "SELECT pa.*, bp.payment_number, u.full_name as doctor_name
                    FROM payment_allocations pa
                    JOIN bulk_payments bp ON pa.bulk_payment_id = bp.bulk_payment_id
                    LEFT JOIN doctors d ON pa.doctor_id = d.doctor_id
                    LEFT JOIN users u ON d.user_id = u.user_id
                    WHERE pa.provider_id = ? AND pa.service_date BETWEEN ? AND ?
                    ORDER BY pa.service_date DESC";
$stmt = $conn->prepare($allocations_sql);
$stmt->bind_param('iss', $provider_id, $date_from, $date_to);
$stmt->execute();
$allocations = $stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Provider Statement')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        @media print {
            .no-print { display: none; }
            .page-header { background: #667eea !important; }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header no-print">
                        <div class="row align-items-center">
                            <div class="col">
                                <h3 class="mb-2"><i class="ri-file-list-line me-2"></i>Provider Statement</h3>
                                <p class="mb-0 opacity-75"><?php echo htmlspecialchars($provider['provider_name']); ?></p>
                            </div>
                            <div class="col-auto">
                                <button onclick="window.print()" class="btn btn-light me-2">
                                    <i class="ri-printer-line me-1"></i>Print
                                </button>
                                <a href="list_external_providers.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-1"></i>Back
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statement Header -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h4><?php echo htmlspecialchars($provider['provider_name']); ?></h4>
                                    <p class="mb-1"><strong>Provider Code:</strong> <?php echo htmlspecialchars($provider['provider_code']); ?></p>
                                    <p class="mb-1"><strong>Type:</strong> <?php echo str_replace('_', ' ', $provider['provider_type']); ?></p>
                                    <?php if ($provider['physical_address']): ?>
                                    <p class="mb-1"><?php echo nl2br(htmlspecialchars($provider['physical_address'])); ?></p>
                                    <?php endif; ?>
                                    <?php if ($provider['email']): ?>
                                    <p class="mb-1"><strong>Email:</strong> <?php echo htmlspecialchars($provider['email']); ?></p>
                                    <?php endif; ?>
                                    <?php if ($provider['phone']): ?>
                                    <p class="mb-1"><strong>Phone:</strong> <?php echo htmlspecialchars($provider['phone']); ?></p>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6 text-end">
                                    <h5>STATEMENT OF ACCOUNT</h5>
                                    <p class="mb-1">
                                        <strong>Period:</strong><br>
                                        <?php echo date('d M Y', strtotime($date_from)); ?> to <?php echo date('d M Y', strtotime($date_to)); ?>
                                    </p>
                                    <p class="mb-1"><strong>Generated:</strong> <?php echo date('d M Y H:i'); ?></p>
                                    <p class="mb-1"><strong>Payment Terms:</strong> <?php echo htmlspecialchars($provider['payment_terms']); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Period Filter -->
                    <div class="card mb-4 no-print">
                        <div class="card-body">
                            <form method="GET" action="">
                                <input type="hidden" name="id" value="<?php echo $provider_id; ?>">
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <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-4">
                                        <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-4 d-flex align-items-end">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-search-line me-1"></i>Update Period
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Account Summary -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <h5 class="card-title mb-4">Account Summary</h5>
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="border-end">
                                        <h6 class="text-muted mb-2">Total Payments</h6>
                                        <h4 class="text-success mb-0">KES <?php echo number_format($summary['total_received'] ?? 0, 2); ?></h4>
                                        <small class="text-muted"><?php echo $summary['payment_count']; ?> payments</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="border-end">
                                        <h6 class="text-muted mb-2">Services Rendered</h6>
                                        <h4 class="text-primary mb-0">KES <?php echo number_format($summary['total_services'] ?? 0, 2); ?></h4>
                                        <small class="text-muted"><?php echo $summary['allocation_count']; ?> allocations</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="border-end">
                                        <h6 class="text-muted mb-2">Current Balance</h6>
                                        <h4 class="text-warning mb-0">KES <?php echo number_format($provider['current_balance'], 2); ?></h4>
                                        <small class="text-muted">Outstanding</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <h6 class="text-muted mb-2">Credit Limit</h6>
                                    <h4 class="mb-0">KES <?php echo number_format($provider['credit_limit'], 2); ?></h4>
                                    <small class="text-muted">Available credit</small>
                                </div>
                            </div>
                            
                            <hr class="my-4">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <h6 class="mb-3">Payment Distribution</h6>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span class="text-muted">Doctor Payments:</span>
                                        <strong class="text-primary">KES <?php echo number_format($summary['total_doctor_share'] ?? 0, 2); ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span class="text-muted">Facility Payments:</span>
                                        <strong class="text-info">KES <?php echo number_format($summary['total_facility_share'] ?? 0, 2); ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between pt-2 border-top">
                                        <strong>Total Allocated:</strong>
                                        <strong>KES <?php echo number_format(($summary['total_doctor_share'] + $summary['total_facility_share']) ?? 0, 2); ?></strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Bulk Payments Received -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <h5 class="card-title mb-4">Bulk Payments Received</h5>
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Payment #</th>
                                            <th>Date</th>
                                            <th>Service Period</th>
                                            <th>Method</th>
                                            <th class="text-end">Amount</th>
                                            <th class="text-end">Allocated</th>
                                            <th class="text-end">Unallocated</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($payments->num_rows > 0): ?>
                                            <?php while ($payment = $payments->fetch_assoc()): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($payment['payment_number']); ?></td>
                                                <td><?php echo date('d M Y', strtotime($payment['payment_date'])); ?></td>
                                                <td>
                                                    <small>
                                                        <?php echo date('d M', strtotime($payment['payment_period_start'])); ?> - 
                                                        <?php echo date('d M Y', strtotime($payment['payment_period_end'])); ?>
                                                    </small>
                                                </td>
                                                <td><small><?php echo str_replace('_', ' ', $payment['payment_method']); ?></small></td>
                                                <td class="text-end"><?php echo number_format($payment['total_amount'], 2); ?></td>
                                                <td class="text-end text-success"><?php echo number_format($payment['allocated_amount'], 2); ?></td>
                                                <td class="text-end text-warning"><?php echo number_format($payment['unallocated_amount'], 2); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php 
                                                        echo $payment['allocation_status'] === 'COMPLETED' ? 'success' : 
                                                            ($payment['allocation_status'] === 'PARTIAL' ? 'warning' : 'secondary'); 
                                                    ?>">
                                                        <?php echo str_replace('_', ' ', $payment['allocation_status']); ?>
                                                    </span>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="8" class="text-center text-muted py-4">No payments in this period</td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Service Allocations -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <h5 class="card-title mb-4">Service Allocations Detail</h5>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Date</th>
                                            <th>Allocation #</th>
                                            <th>Bulk Payment</th>
                                            <th>Service Category</th>
                                            <th>Doctor</th>
                                            <th class="text-end">Service Cost</th>
                                            <th class="text-end">Doctor Share</th>
                                            <th class="text-end">Facility Share</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($allocations->num_rows > 0): ?>
                                            <?php while ($alloc = $allocations->fetch_assoc()): ?>
                                            <tr>
                                                <td><?php echo date('d M Y', strtotime($alloc['service_date'])); ?></td>
                                                <td><small><?php echo htmlspecialchars($alloc['allocation_number']); ?></small></td>
                                                <td><small><?php echo htmlspecialchars($alloc['payment_number']); ?></small></td>
                                                <td><small><?php echo ucfirst(strtolower($alloc['service_category'])); ?></small></td>
                                                <td><small><?php echo htmlspecialchars($alloc['doctor_name'] ?: 'Facility Only'); ?></small></td>
                                                <td class="text-end"><?php echo number_format($alloc['total_service_cost'], 2); ?></td>
                                                <td class="text-end text-primary"><?php echo number_format($alloc['doctor_allocation'], 2); ?></td>
                                                <td class="text-end text-info"><?php echo number_format($alloc['facility_allocation'], 2); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php 
                                                        echo $alloc['allocation_status'] === 'APPROVED' ? 'success' : 
                                                            ($alloc['allocation_status'] === 'PAID' ? 'primary' : 'warning'); 
                                                    ?>">
                                                        <?php echo str_replace('_', ' ', $alloc['allocation_status']); ?>
                                                    </span>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="9" class="text-center text-muted py-4">No allocations in this period</td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Footer Note -->
                    <div class="card">
                        <div class="card-body">
                            <p class="text-muted mb-0">
                                <strong>Note:</strong> This statement is generated for the period 
                                <?php echo date('d M Y', strtotime($date_from)); ?> to <?php echo date('d M Y', strtotime($date_to)); ?>. 
                                For any queries or discrepancies, please contact our accounts department.
                            </p>
                        </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>
        flatpickr('.datepicker', {
            dateFormat: 'Y-m-d',
            allowInput: true
        });
    </script>
</body>
</html>