<?php
// sales_view.php
session_start();
require_once '../config/db_connect.php';

// Handle POST requests first (clear balance) BEFORE any output
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clear_balance'])) {
    // Initialize session and database
    if (!isset($_SESSION['user'])) {
        header("Location: ../auth/login.php");
        exit;
    }
    
    $user = $_SESSION['user'];
    $user_role = $user['role'] ?? 'cashier';
    $sale_id = isset($_POST['sale_id']) ? intval($_POST['sale_id']) : 0;
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'CASH';
    
    if ($sale_id <= 0 || $amount <= 0) {
        $error_message = "Invalid payment details.";
        // Store error in session to display later
        $_SESSION['error_message'] = $error_message;
        header("Location: sales_view.php?id=$sale_id");
        exit;
    }
    
    // Check permissions
    if (!in_array($user_role, ['admin', 'pharmacist'])) {
        $_SESSION['error_message'] = "You don't have permission to record payments.";
        header("Location: sales_view.php?id=$sale_id");
        exit;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Get sale details
        $stmt = $pdo->prepare("SELECT total, paid, shop_id FROM sales WHERE id = ?");
        $stmt->execute([$sale_id]);
        $sale = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$sale) {
            throw new Exception("Sale not found.");
        }
        
        $balance = $sale['total'] - $sale['paid'];
        
        // Validate amount
        if ($amount > $balance) {
            throw new Exception("Payment amount cannot exceed the balance of " . number_format($balance, 2));
        }
        
        $new_paid = $sale['paid'] + $amount;
        $new_balance = $sale['total'] - $new_paid;
        $new_status = ($new_balance <= 0) ? 'paid' : 'partially_paid';
        
        // Update sale
        $stmt = $pdo->prepare("UPDATE sales SET paid = ?, status = ? WHERE id = ?");
        $stmt->execute([$new_paid, $new_status, $sale_id]);
        
        // Record payment
        $stmt = $pdo->prepare("INSERT INTO payments (sale_id, amount, method, created_by, shop_id) 
                               VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$sale_id, $amount, $payment_method, $user['id'], $sale['shop_id']]);
        
        $pdo->commit();
        
        // Store success message in session
        $_SESSION['success_message'] = "Payment of " . number_format($amount, 2) . " recorded successfully.";
        
        // Redirect to same page
        header("Location: sales_view.php?id=$sale_id");
        exit;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = "Error recording payment: " . $e->getMessage();
        header("Location: sales_view.php?id=$sale_id");
        exit;
    }
}

// Now continue with normal page rendering
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// Check if user is logged in (for GET requests)
if (!isset($_SESSION['user'])) {
    header("Location: ../auth/login.php");
    exit;
}

$user = $_SESSION['user'];
$user_role = $user['role'] ?? 'cashier';
$user_shop_id = $user['shop_id'] ?? 0;

// Get sale ID from URL
$sale_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($sale_id <= 0) {
    header("Location: dashboard.php");
    exit;
}

// Fetch sale details
$params = [$sale_id];
$sql = "SELECT 
           s.*,
           COALESCE(c.name, 'Walk-in Customer') as customer_name,
           c.phone as customer_phone,
           c.address as customer_address,
           u.fullname as cashier,
           sh.name as shop_name
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        LEFT JOIN users u ON s.created_by = u.id
        LEFT JOIN shops sh ON s.shop_id = sh.id
        WHERE s.id = ?";
        
if ($user_role !== 'admin') {
    $sql .= " AND s.shop_id = ?";
    $params[] = $user_shop_id;
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sale) {
    echo "<div class='alert alert-danger'>Sale not found or you don't have permission to view it.</div>";
    require_once '../includes/footer.php';
    exit;
}

// Fetch sale line items
$sql = "SELECT 
           sl.*,
           p.name as product_name,
           p.sku,
           p.unit,
           pb.batch_no,
           pb.expiry_date
        FROM sale_lines sl
        JOIN products p ON sl.product_id = p.id
        LEFT JOIN product_batches pb ON sl.batch_id = pb.id
        WHERE sl.sale_id = ?
        ORDER BY sl.id";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sale_id]);
$sale_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch payment history
$sql = "SELECT 
           p.*,
           u.fullname as received_by
        FROM payments p
        LEFT JOIN users u ON p.created_by = u.id
        WHERE p.sale_id = ?
        ORDER BY p.paid_at";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sale_id]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals
$subtotal = 0;
$total_discount = 0;
$vat_total = 0;

foreach ($sale_items as $item) {
    $line_total = $item['qty'] * $item['unit_price'];
    $discount_amount = $line_total * ($item['discount'] / 100);
    $after_discount = $line_total - $discount_amount;
    $vat_amount = $after_discount * 0.18; // Assuming 18% VAT, adjust as needed
    
    $subtotal += $after_discount;
    $total_discount += $discount_amount;
    $vat_total += $vat_amount;
}

$grand_total = $subtotal + $vat_total;
$balance = $sale['total'] - $sale['paid'];

// Get messages from session if they exist
$success_message = $_SESSION['success_message'] ?? '';
$error_message = $_SESSION['error_message'] ?? '';
unset($_SESSION['success_message'], $_SESSION['error_message']);
?>

<style>
.main-content-wrapper {
    padding: 20px;
    min-height: calc(100vh - 80px);
    background-color: #f5f7fb;
}

.card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.badge {
    font-size: 12px;
    padding: 5px 10px;
}

.table th {
    background-color: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
}

.balance-highlight {
    border-left: 4px solid #ffc107;
    background-color: #fff9e6;
}

.payment-success {
    border-left: 4px solid #28a745;
    background-color: #f0fff4;
}

.alert {
    border-radius: 8px;
    border: none;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .main-content-wrapper {
        padding: 15px 10px;
    }
}
</style>

<div class="main-content-wrapper" id="mainContent">
    <div class="container-fluid">
        <!-- Header -->
        <div class="card p-3 mb-4">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h3>Sale Details</h3>
                    <p class="mb-0">Invoice: <strong><?=htmlspecialchars($sale['invoice_no'])?></strong></p>
                </div>
                <div class="text-right">
                    <a href="dashboard.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                    <button onclick="window.print()" class="btn btn-info ml-2">
                        <i class="fas fa-print"></i> Print
                    </button>
                </div>
            </div>
        </div>

        <!-- Display messages -->
        <?php if(!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?=htmlspecialchars($success_message)?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>
        
        <?php if(!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?=htmlspecialchars($error_message)?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Left Column: Sale Details -->
            <div class="col-md-8">
                <!-- Sale Information -->
                <div class="card p-3 mb-4">
                    <h5 class="mb-3">Sale Information</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr>
                                    <th width="40%">Invoice No:</th>
                                    <td><?=htmlspecialchars($sale['invoice_no'])?></td>
                                </tr>
                                <tr>
                                    <th>Date & Time:</th>
                                    <td><?=date('d-M-Y H:i:s', strtotime($sale['sale_date']))?></td>
                                </tr>
                                <tr>
                                    <th>Shop:</th>
                                    <td><?=htmlspecialchars($sale['shop_name'])?></td>
                                </tr>
                                <tr>
                                    <th>Cashier:</th>
                                    <td><?=htmlspecialchars($sale['cashier'])?></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr>
                                    <th width="40%">Customer:</th>
                                    <td><?=htmlspecialchars($sale['customer_name'])?></td>
                                </tr>
                                <tr>
                                    <th>Phone:</th>
                                    <td><?=htmlspecialchars($sale['customer_phone'])?></td>
                                </tr>
                                <tr>
                                    <th>Address:</th>
                                    <td><?=htmlspecialchars($sale['customer_address'])?></td>
                                </tr>
                                <tr>
                                    <th>Status:</th>
                                    <td>
                                        <span class="badge badge-<?= 
                                            $sale['status'] == 'paid' ? 'success' : 
                                            ($sale['status'] == 'partially_paid' ? 'warning' : 'secondary')
                                        ?>">
                                            <?=ucfirst(str_replace('_', ' ', $sale['status']))?>
                                        </span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Sale Items -->
                <div class="card p-3 mb-4">
                    <h5 class="mb-3">Sale Items</h5>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="thead-light">
                                <tr>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>Batch</th>
                                    <th class="text-center">Qty</th>
                                    <th class="text-center">Unit Price</th>
                                    <th class="text-center">Disc %</th>
                                    <th class="text-right">Line Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($sale_items as $index => $item): 
                                    $line_total = $item['qty'] * $item['unit_price'];
                                    $discount_amount = $line_total * ($item['discount'] / 100);
                                    $final_line_total = $line_total - $discount_amount;
                                ?>
                                <tr>
                                    <td><?=$index + 1?></td>
                                    <td>
                                        <strong><?=htmlspecialchars($item['product_name'])?></strong><br>
                                        <small class="text-muted">SKU: <?=htmlspecialchars($item['sku'])?></small>
                                    </td>
                                    <td>
                                        <?=htmlspecialchars($item['batch_no'])?>
                                        <?php if($item['expiry_date']): ?>
                                            <br><small class="text-muted">Exp: <?=date('M Y', strtotime($item['expiry_date']))?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center"><?=$item['qty']?> <?=htmlspecialchars($item['unit'])?></td>
                                    <td class="text-center"><?=number_format($item['unit_price'], 2)?></td>
                                    <td class="text-center"><?=number_format($item['discount'], 2)?>%</td>
                                    <td class="text-right"><?=number_format($final_line_total, 2)?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Payment History -->
                <?php if(!empty($payments)): ?>
                <div class="card p-3">
                    <h5 class="mb-3">Payment History</h5>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="thead-light">
                                <tr>
                                    <th>Date & Time</th>
                                    <th>Amount</th>
                                    <th>Method</th>
                                    <th>Received By</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($payments as $payment): ?>
                                <tr class="payment-success">
                                    <td><?=date('d-M-Y H:i', strtotime($payment['paid_at']))?></td>
                                    <td class="text-success font-weight-bold"><?=number_format($payment['amount'], 2)?></td>
                                    <td><?=htmlspecialchars($payment['method'])?></td>
                                    <td><?=htmlspecialchars($payment['received_by'])?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Right Column: Payment Summary & Actions -->
            <div class="col-md-4">
                <!-- Payment Summary -->
                <div class="card p-3 mb-4">
                    <h5 class="mb-3">Payment Summary</h5>
                    <table class="table table-sm">
                        <tr>
                            <th>Subtotal:</th>
                            <td class="text-right"><?=number_format($subtotal, 2)?></td>
                        </tr>
                        <tr>
                            <th>Discount:</th>
                            <td class="text-right text-danger">-<?=number_format($total_discount, 2)?></td>
                        </tr>
                        <tr>
                            <th>VAT (18%):</th>
                            <td class="text-right"><?=number_format($vat_total, 2)?></td>
                        </tr>
                        <tr class="table-success font-weight-bold">
                            <th>GRAND TOTAL:</th>
                            <td class="text-right"><?=number_format($grand_total, 2)?></td>
                        </tr>
                        <tr class="font-weight-bold">
                            <th>Amount Paid:</th>
                            <td class="text-right text-success"><?=number_format($sale['paid'], 2)?></td>
                        </tr>
                        <tr class="font-weight-bold <?= $balance > 0 ? 'balance-highlight' : '' ?>">
                            <th>BALANCE:</th>
                            <td class="text-right <?= $balance > 0 ? 'text-danger' : 'text-success' ?>">
                                <?=number_format($balance, 2)?>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- Clear Balance Form (if there's a balance) -->
                <?php if($balance > 0 && ($user_role === 'admin' || $user_role === 'pharmacist')): ?>
                <div class="card p-3">
                    <h5 class="mb-3">Record Payment</h5>
                    <form method="POST" action="sales_view.php">
                        <input type="hidden" name="sale_id" value="<?=$sale_id?>">
                        
                        <div class="form-group">
                            <label>Current Balance</label>
                            <input type="text" class="form-control font-weight-bold text-danger" 
                                   value="<?=number_format($balance, 2)?>" readonly>
                        </div>
                        
                        <div class="form-group">
                            <label>Payment Amount *</label>
                            <input type="number" name="amount" id="paymentAmount" class="form-control" 
                                   step="0.01" min="0.01" max="<?=$balance?>" 
                                   value="<?=$balance?>" required>
                            <small class="form-text text-muted">Enter amount to be paid now.</small>
                        </div>
                        
                        <div class="form-group">
                            <label>Payment Method</label>
                            <select name="payment_method" class="form-control" required>
                                <option value="CASH">Cash</option>
                                <option value="M-PESA">M-PESA</option>
                                <option value="TIGO-PESA">Tigo Pesa</option>
                                <option value="AIRTEL-MONEY">Airtel Money</option>
                                <option value="CARD">Card</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>New Balance After Payment</label>
                            <input type="text" class="form-control font-weight-bold" 
                                   id="newBalancePreview" readonly>
                        </div>
                        
                        <button type="submit" name="clear_balance" class="btn btn-success btn-block">
                            <i class="fas fa-check-circle"></i> Record Payment
                        </button>
                    </form>
                </div>
                <?php endif; ?>

                <!-- Sale Actions -->
                <div class="card p-3 mt-4">
                    <h5 class="mb-3">Quick Actions</h5>
                    <div class="d-grid gap-2">
                        <a href="print_receipt.php?sale_id=<?=$sale_id?>" target="_blank" class="btn btn-info">
                            <i class="fas fa-receipt"></i> Print Receipt
                        </a>
                        <?php if($user_role === 'admin'): ?>
                        <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#cancelSaleModal">
                            <i class="fas fa-times"></i> Cancel Sale
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Cancel Sale Modal (Optional) -->
<?php if($user_role === 'admin'): ?>
<div class="modal fade" id="cancelSaleModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Cancel Sale</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i> This action cannot be undone. 
                    All stock will be returned to inventory.
                </div>
                <p>Are you sure you want to cancel this sale?</p>
                <p><strong>Invoice:</strong> <?=htmlspecialchars($sale['invoice_no'])?></p>
                <p><strong>Total Amount:</strong> <?=number_format($sale['total'], 2)?></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">No, Keep Sale</button>
                <a href="cancel_sale.php?id=<?=$sale_id?>" class="btn btn-danger">Yes, Cancel Sale</a>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Calculate new balance preview
document.addEventListener('DOMContentLoaded', function() {
    const amountInput = document.getElementById('paymentAmount');
    const newBalancePreview = document.getElementById('newBalancePreview');
    
    if (amountInput && newBalancePreview) {
        const balance = <?=$balance?>;
        
        function updateBalancePreview() {
            const payment = parseFloat(amountInput.value) || 0;
            const newBalance = Math.max(0, balance - payment);
            newBalancePreview.value = newBalance.toFixed(2);
            
            // Color code
            if (newBalance === 0) {
                newBalancePreview.className = 'form-control font-weight-bold text-success';
            } else if (newBalance > 0) {
                newBalancePreview.className = 'form-control font-weight-bold text-warning';
            }
        }
        
        amountInput.addEventListener('input', updateBalancePreview);
        updateBalancePreview(); // Initial calculation
    }
    
    // Auto-dismiss alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
});
</script>

<?php require_once '../includes/footer.php'; ?>