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

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

// Include header files
include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Client Debt Statement')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <style>
        .statement-header {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 0.25rem;
            margin-bottom: 1.5rem;
        }
        .customer-details {
            margin-bottom: 1.5rem;
        }
        .transaction-amount-positive {
            color: #dc3545;
        }
        .transaction-amount-negative {
            color: #198754;
        }
        .summary-card {
            background-color: #f8f9fa;
            padding: 1rem;
            border-radius: 0.25rem;
        }
        .balance-amount {
            font-size: 1.25rem;
            font-weight: bold;
        }
        .balance-positive {
            color: #dc3545;
        }
        .balance-negative {
            color: #198754;
        }
        .select2-container {
            width: 100% !important;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Financial Management', 'title' => 'Client Debt Statement')); ?>

                    <!-- Success/Error Messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Generate Statement</h4>
                                </div>
                                <div class="card-body">
                                    <form method="GET" action="" id="statement-form">
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="customer_id" class="form-label">Customer</label>
                                                <select class="form-select select2" id="customer_id" name="customer_id" required>
                                                    <option value="">Select a customer</option>
                                                    <?php foreach ($customers as $customer): ?>
                                                    <option value="<?php echo $customer['customer_id']; ?>" <?php echo ($selectedCustomerId == $customer['customer_id']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <label for="currency" class="form-label">Currency</label>
                                                <select class="form-select" id="currency" name="currency" required>
                                                    <?php foreach ($currencies as $curr): ?>
                                                    <option value="<?php echo $curr; ?>" <?php echo ($currency == $curr) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($curr); ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Date Range</label>
                                                <div class="btn-group w-100">
                                                    <button type="button" class="btn btn-outline-secondary date-preset" data-range="month">This Month</button>
                                                    <button type="button" class="btn btn-outline-secondary date-preset" data-range="quarter">This Quarter</button>
                                                    <button type="button" class="btn btn-outline-secondary date-preset" data-range="year">This Year</button>
                                                    <button type="button" class="btn btn-outline-secondary date-preset" data-range="all">All Time</button>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="start_date" class="form-label">Start Date</label>
                                                <input type="text" class="form-control flatpickr-date" id="start_date" name="start_date" value="<?php echo $startDate; ?>" required>
                                            </div>
                                            <div class="col-md-4">
                                                <label for="end_date" class="form-label">End Date</label>
                                                <input type="text" class="form-control flatpickr-date" id="end_date" name="end_date" value="<?php echo $endDate; ?>" required>
                                            </div>
                                            <div class="col-md-4 d-flex align-items-end">
                                                <button type="submit" class="btn btn-primary me-2">
                                                    <i class="ri-search-line me-1"></i> Generate Statement
                                                </button>
                                                <?php if ($selectedCustomerId > 0 && $statement): ?>
                                                <button type="submit" class="btn btn-success" name="export_pdf" value="1">
                                                    <i class="ri-file-pdf-line me-1"></i> Export PDF
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($selectedCustomerId > 0 && $statement && $customerDetails): ?>
                    <div class="row">
                        <div class="col-xl-12">
                            <!-- Statement Header -->
                            <div class="statement-header">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="customer-details">
                                            <h5><?php echo htmlspecialchars($customerDetails['first_name'] . ' ' . $customerDetails['last_name']); ?></h5>
                                            <?php if (!empty($customerDetails['address'])): ?>
                                            <p class="mb-1"><?php echo htmlspecialchars($customerDetails['address']); ?></p>
                                            <?php endif; ?>
                                            <?php if (!empty($customerDetails['city']) || !empty($customerDetails['country'])): ?>
                                            <p class="mb-1">
                                                <?php 
                                                $location = [];
                                                if (!empty($customerDetails['city'])) $location[] = $customerDetails['city'];
                                                if (!empty($customerDetails['country'])) $location[] = $customerDetails['country'];
                                                echo htmlspecialchars(implode(', ', $location));
                                                ?>
                                            </p>
                                            <?php endif; ?>
                                            <?php if (!empty($customerDetails['phone_number'])): ?>
                                            <p class="mb-1">Tel: <?php echo htmlspecialchars($customerDetails['phone_number']); ?></p>
                                            <?php endif; ?>
                                            <?php if (!empty($customerDetails['email'])): ?>
                                            <p class="mb-1">Email: <?php echo htmlspecialchars($customerDetails['email']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="col-md-6 text-md-end">
                                        <h5>Statement Period</h5>
                                        <p class="mb-1"><?php echo date('d M Y', strtotime($startDate)); ?> - <?php echo date('d M Y', strtotime($endDate)); ?></p>
                                        <p class="mb-1">Currency: <?php echo htmlspecialchars($currency); ?></p>
                                        <p class="mb-1">Generated: <?php echo date('d M Y H:i'); ?></p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Statement Summary -->
                            <div class="row mb-4">
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-body summary-card">
                                            <h6 class="card-title">Opening Balance</h6>
                                            <p class="balance-amount <?php echo $statement['opening_balance'] > 0 ? 'balance-positive' : ($statement['opening_balance'] < 0 ? 'balance-negative' : ''); ?>">
                                                <?php echo htmlspecialchars($currency . ' ' . number_format($statement['opening_balance'], 2)); ?>
                                            </p>
                                            <small class="text-muted">Balance as of <?php echo date('d M Y', strtotime($startDate)); ?></small>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-body summary-card">
                                            <h6 class="card-title">Transaction Total</h6>
                                            <?php
                                            $transactionTotal = 0;
                                            foreach ($statement['transactions'] as $transaction) {
                                                $transactionTotal += $transaction['amount'];
                                            }
                                            ?>
                                            <p class="balance-amount <?php echo $transactionTotal > 0 ? 'balance-positive' : ($transactionTotal < 0 ? 'balance-negative' : ''); ?>">
                                                <?php echo htmlspecialchars($currency . ' ' . number_format($transactionTotal, 2)); ?>
                                            </p>
                                            <small class="text-muted"><?php echo count($statement['transactions']); ?> transactions in period</small>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-body summary-card">
                                            <h6 class="card-title">Closing Balance</h6>
                                            <p class="balance-amount <?php echo $statement['closing_balance'] > 0 ? 'balance-positive' : ($statement['closing_balance'] < 0 ? 'balance-negative' : ''); ?>">
                                                <?php echo htmlspecialchars($currency . ' ' . number_format($statement['closing_balance'], 2)); ?>
                                            </p>
                                            <small class="text-muted">Balance as of <?php echo date('d M Y', strtotime($endDate)); ?></small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Transaction List -->
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">Transaction History</h5>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($statement['transactions'])): ?>
                                    <div class="text-center py-4">
                                        <div class="avatar-md mx-auto mb-3">
                                            <div class="avatar-title bg-light text-primary rounded-circle">
                                                <i class="ri-exchange-funds-line fs-24"></i>
                                            </div>
                                        </div>
                                        <h5 class="mb-1">No transactions found</h5>
                                        <p class="text-muted">No transactions were recorded during this period.</p>
                                    </div>
                                    <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-striped mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Type</th>
                                                    <th>Reference</th>
                                                    <th>Notes</th>
                                                    <th>Amount</th>
                                                    <th>Balance</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <!-- Opening Balance Row -->
                                                <tr class="table-light">
                                                    <td><?php echo date('d M Y', strtotime($startDate)); ?></td>
                                                    <td><span class="badge bg-secondary">Opening Balance</span></td>
                                                    <td>-</td>
                                                    <td>Balance brought forward</td>
                                                    <td>-</td>
                                                    <td class="<?php echo $statement['opening_balance'] > 0 ? 'transaction-amount-positive' : ($statement['opening_balance'] < 0 ? 'transaction-amount-negative' : ''); ?>">
                                                        <?php echo htmlspecialchars($currency . ' ' . number_format($statement['opening_balance'], 2)); ?>
                                                    </td>
                                                </tr>
                                                
                                                <?php 
                                                $runningBalance = $statement['opening_balance'];
                                                foreach ($statement['transactions'] as $transaction): 
                                                    $runningBalance += $transaction['amount'];
                                                    
                                                    // Set badge color based on transaction type
                                                    $typeClass = '';
                                                    switch ($transaction['transaction_type']) {
                                                        case 'invoice':
                                                            $typeClass = 'bg-primary';
                                                            break;
                                                        case 'payment':
                                                            $typeClass = 'bg-success';
                                                            break;
                                                        case 'credit_note':
                                                            $typeClass = 'bg-info';
                                                            break;
                                                        case 'debit_note':
                                                            $typeClass = 'bg-warning';
                                                            break;
                                                        case 'adjustment':
                                                            $typeClass = 'bg-secondary';
                                                            break;
                                                        default:
                                                            $typeClass = 'bg-dark';
                                                    }
                                                ?>
                                                <tr>
                                                    <td><?php echo date('d M Y', strtotime($transaction['transaction_date'])); ?></td>
                                                    <td><span class="badge <?php echo $typeClass; ?>"><?php echo ucfirst(str_replace('_', ' ', $transaction['transaction_type'])); ?></span></td>
                                                    <td><?php echo htmlspecialchars($transaction['reference_id'] ?: 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($transaction['notes']); ?></td>
                                                    <td class="<?php echo $transaction['amount'] > 0 ? 'transaction-amount-positive' : 'transaction-amount-negative'; ?>">
                                                        <?php echo htmlspecialchars($currency . ' ' . number_format($transaction['amount'], 2)); ?>
                                                    </td>
                                                    <td class="<?php echo $runningBalance > 0 ? 'transaction-amount-positive' : ($runningBalance < 0 ? 'transaction-amount-negative' : ''); ?>">
                                                        <?php echo htmlspecialchars($currency . ' ' . number_format($runningBalance, 2)); ?>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                                
                                                <!-- Closing Balance Row -->
                                                <tr class="table-light">
                                                    <td><?php echo date('d M Y', strtotime($endDate)); ?></td>
                                                    <td><span class="badge bg-secondary">Closing Balance</span></td>
                                                    <td>-</td>
                                                    <td>Balance carried forward</td>
                                                    <td>-</td>
                                                    <td class="<?php echo $statement['closing_balance'] > 0 ? 'transaction-amount-positive' : ($statement['closing_balance'] < 0 ? 'transaction-amount-negative' : ''); ?>">
                                                        <strong><?php echo htmlspecialchars($currency . ' ' . number_format($statement['closing_balance'], 2)); ?></strong>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize flatpickr for date inputs
            const startDatePicker = flatpickr("#start_date", {
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            const endDatePicker = flatpickr("#end_date", {
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            // Initialize Select2
            $('.select2').select2({
                placeholder: "Select a customer",
                allowClear: true
            });
            
            // Date range preset buttons
            document.querySelectorAll('.date-preset').forEach(button => {
                button.addEventListener('click', function() {
                    const range = this.getAttribute('data-range');
                    let startDate, endDate;
                    const today = new Date();
                    endDate = new Date(today); // End date is today
                    
                    switch(range) {
                        case 'month':
                            // First day of current month
                            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
                            break;
                        case 'quarter':
                            // First day of current quarter
                            const quarter = Math.floor(today.getMonth() / 3);
                            startDate = new Date(today.getFullYear(), quarter * 3, 1);
                            break;
                        case 'year':
                            // First day of current year
                            startDate = new Date(today.getFullYear(), 0, 1);
                            break;
                        case 'all':
                            // Use a date far in the past
                            startDate = new Date(2000, 0, 1);
                            break;
                    }
                    
                    // Update the date pickers
                    startDatePicker.setDate(startDate);
                    endDatePicker.setDate(endDate);
                    
                    // Update active state of buttons
                    document.querySelectorAll('.date-preset').forEach(btn => {
                        btn.classList.remove('active', 'btn-secondary');
                        btn.classList.add('btn-outline-secondary');
                    });
                    this.classList.remove('btn-outline-secondary');
                    this.classList.add('active', 'btn-secondary');
                });
            });
            
            // Form validation
            const form = document.getElementById('statement-form');
            if (form) {
                form.addEventListener('submit', function(event) {
                    let isValid = true;
                    const customer = document.getElementById('customer_id');
                    const startDate = document.getElementById('start_date');
                    const endDate = document.getElementById('end_date');
                    
                    // Reset previous validation
                    form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
                    
                    // Validate customer
                    if (!customer.value) {
                        customer.classList.add('is-invalid');
                        isValid = false;
                    }
                    
                    // Validate start date
                    if (!startDate.value) {
                        startDate.classList.add('is-invalid');
                        isValid = false;
                    }
                    
                    // Validate end date
                    if (!endDate.value) {
                        endDate.classList.add('is-invalid');
                        isValid = false;
                    }
                    
                    // Validate date range
                    if (startDate.value && endDate.value) {
                        const start = new Date(startDate.value);
                        const end = new Date(endDate.value);
                        
                        if (start > end) {
                            startDate.classList.add('is-invalid');
                            endDate.classList.add('is-invalid');
                            alert('Start date cannot be after end date');
                            isValid = false;
                        }
                    }
                    
                    if (!isValid) {
                        event.preventDefault();
                    }
                });
            }
        });
    </script>
</body>

</html>