<?php
session_start();
include 'layouts/dbconn.php';

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

// Get debit ID from URL
$debit_id = $_GET['id'] ?? null;
if (!$debit_id) {
    header('Location: view_debits.php');
    exit();
}

// Fetch debit note details
$sql = "SELECT d.*,
        c.corporate as corporate_name,
        p.surname as family_surname,
        p.first_name as family_first_name,
        u.full_name as created_by_name
    FROM premium_debit_notes d
    LEFT JOIN corporate c ON d.corp_id = c.corp_id
    LEFT JOIN principal_applicant p ON d.family_no = p.family_no
    LEFT JOIN users u ON d.created_by = u.user_id
    WHERE d.debit_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $debit_id);
$stmt->execute();
$debit = $stmt->get_result()->fetch_assoc();

if (!$debit) {
    header('Location: view_debits.php');
    exit();
}

// Fetch debit items
$sql = "SELECT di.*,
        b.benefit as benefit_name,
        m.surname as member_surname,
        m.first_name as member_first_name
    FROM premium_debit_items di
    LEFT JOIN benefit b ON di.benefit_code = b.code
    LEFT JOIN member_info m ON di.member_no = m.member_no
    WHERE di.debit_id = ?
    ORDER BY di.item_id";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $debit_id);
$stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Debit Note')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance', 'title' => 'View Debit Note')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Debit Note Details</h4>
                                    <div class="flex-shrink-0">
                                        <div class="d-flex flex-wrap gap-2">
                                            <button type="button" class="btn btn-primary btn-sm" onclick="window.print();">
                                                <i class="ri-printer-line align-bottom me-1"></i> Print
                                            </button>
                                            <?php if ($debit['status'] === 'UNALLOCATED'): ?>
                                            <a href="add_receipt.php?id=<?php echo $debit_id; ?>" class="btn btn-success btn-sm">
                                                <i class="ri-currency-line align-bottom me-1"></i> Receipt
                                            </a>
                                            <?php endif; ?>
                                            <?php if ($debit['status'] === 'UNALLOCATED'): ?>
                                            <a href="edit_debit.php?id=<?php echo $debit_id; ?>" class="btn btn-info btn-sm">
                                                <i class="ri-edit-2-line align-bottom me-1"></i> Edit
                                            </a>
                                            <?php endif; ?>
                                            <a href="view_debits.php" class="btn btn-light btn-sm">
                                                <i class="ri-arrow-left-line align-bottom me-1"></i> Back
                                            </a>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-sm-6">
                                            <div class="mb-4">
                                                <h6 class="text-muted mb-3">Debit Details</h6>
                                                <table class="table table-sm table-borderless mb-0">
                                                    <tr>
                                                        <th width="140">Debit Number:</th>
                                                        <td><?php echo htmlspecialchars($debit['debit_no']); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Date:</th>
                                                        <td><?php echo date('d M Y', strtotime($debit['debit_date'])); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Type:</th>
                                                        <td><?php echo htmlspecialchars($debit['debit_type']); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Status:</th>
                                                        <td>
                                                            <span class="badge bg-<?php 
                                                                echo $debit['status'] === 'POSTED' ? 'success' : 
                                                                    ($debit['status'] === 'DRAFT' ? 'warning' : 'danger'); 
                                                            ?>">
                                                                <?php echo htmlspecialchars($debit['status']); ?>
                                                            </span>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <th>Created By:</th>
                                                        <td><?php echo htmlspecialchars($debit['created_by_name']); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Created At:</th>
                                                        <td><?php echo date('d M Y H:i', strtotime($debit['created_at'])); ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>

                                        <div class="col-sm-6">
                                            <div class="mb-4">
                                                <h6 class="text-muted mb-3">
                                                    <?php echo $debit['debit_type'] === 'SCHEME' ? 'Corporate' : 'Family'; ?> Details
                                                </h6>
                                                <table class="table table-sm table-borderless mb-0">
                                                    <?php if ($debit['debit_type'] === 'SCHEME'): ?>
                                                    <tr>
                                                        <th width="140">Corporate:</th>
                                                        <td><?php echo htmlspecialchars($debit['corporate_name']); ?></td>
                                                    </tr>
                                                    <?php else: ?>
                                                    <tr>
                                                        <th width="140">Family No:</th>
                                                        <td><?php echo htmlspecialchars($debit['family_no']); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Principal:</th>
                                                        <td>
                                                            <?php 
                                                            echo htmlspecialchars($debit['family_surname'] . ' ' . 
                                                                $debit['family_first_name']); 
                                                            ?>
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    <tr>
                                                        <th>Period From:</th>
                                                        <td><?php echo date('d M Y', strtotime($debit['period_from'])); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Period To:</th>
                                                        <td><?php echo date('d M Y', strtotime($debit['period_to'])); ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="table-responsive mt-4">
                                        <table class="table table-bordered align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>#</th>
                                                    <th>Benefit</th>
                                                    <th>Member</th>
                                                    <th class="text-end">Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $total = 0;
                                                foreach ($items as $index => $item): 
                                                    $total += $item['amount'];
                                                ?>
                                                <tr>
                                                    <td><?php echo $index + 1; ?></td>
                                                    <td><?php echo htmlspecialchars($item['benefit_name']); ?></td>
                                                    <td>
                                                        <?php
                                                        echo htmlspecialchars($item['member_no']);
                                                        if ($item['member_surname']) {
                                                            echo ' - ' . htmlspecialchars($item['member_surname'] . ' ' . 
                                                                $item['member_first_name']);
                                                        }
                                                        ?>
                                                    </td>
                                                    <td class="text-end">
                                                        <?php echo number_format($item['amount'], 2); ?>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <th colspan="3" class="text-end">Total:</th>
                                                    <th class="text-end"><?php echo number_format($total, 2); ?></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>