<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest Statement
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 3) . '/config/config.php';
require_once dirname(__DIR__, 3) . '/config/constants.php';
require_once dirname(__DIR__, 3) . '/config/database.php';
require_once dirname(__DIR__, 3) . '/config/helpers.php';
require_once dirname(__DIR__, 3) . '/config/auth.php';
require_once dirname(__DIR__, 3) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('billing.debtors.view');

// Set page title
$page_title = 'Guest Statement';

// Get current user
$current_user = current_user();

// Get guest ID from URL
$guest_id = isset($_GET['guest_id']) ? (int)$_GET['guest_id'] : 0;

if (!$guest_id) {
    set_flash_message('danger', 'Invalid guest ID');
    redirect('index.php');
}

// Get guest information
$guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id]);

if (!$guest) {
    set_flash_message('danger', 'Guest not found');
    redirect('index.php');
}

// Get date range from request
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-3 months'));
$date_to = $_GET['date_to'] ?? date('Y-m-d');

// Get all invoices for this guest
$invoices = db_fetch_all("
    SELECT 
        i.*,
        DATEDIFF(CURDATE(), i.due_date) as days_overdue
    FROM invoices i
    WHERE i.guest_id = ?
    ORDER BY i.invoice_date DESC
", [$guest_id]);

// Get all payments for this guest
$payments = db_fetch_all("
    SELECT p.*, pm.method_name
    FROM payments p
    JOIN payment_methods pm ON p.payment_method_id = pm.payment_method_id
    WHERE p.guest_id = ?
    ORDER BY p.payment_date DESC
", [$guest_id]);

// Calculate summary statistics
$summary = [
    'total_invoiced' => 0,
    'total_paid' => 0,
    'outstanding' => 0,
    'overdue' => 0,
    'invoice_count' => count($invoices),
    'payment_count' => count($payments)
];

foreach ($invoices as $invoice) {
    $summary['total_invoiced'] += $invoice['total_amount'];
    $summary['total_paid'] += $invoice['paid_amount'];
    if ($invoice['balance'] > 0) {
        $summary['outstanding'] += $invoice['balance'];
        if ($invoice['status'] == 'overdue') {
            $summary['overdue'] += $invoice['balance'];
        }
    }
}

// Combine and sort all transactions for statement
$transactions = [];

// Add invoices
foreach ($invoices as $invoice) {
    $transactions[] = [
        'date' => $invoice['invoice_date'],
        'type' => 'invoice',
        'reference' => $invoice['invoice_number'],
        'description' => 'Invoice',
        'debit' => $invoice['total_amount'],
        'credit' => 0,
        'balance' => 0, // Will calculate running balance
        'status' => $invoice['status']
    ];
}

// Add payments
foreach ($payments as $payment) {
    $transactions[] = [
        'date' => date('Y-m-d', strtotime($payment['payment_date'])),
        'type' => 'payment',
        'reference' => $payment['payment_number'],
        'description' => 'Payment - ' . $payment['method_name'],
        'debit' => 0,
        'credit' => $payment['amount'],
        'balance' => 0,
        'status' => $payment['status']
    ];
}

// Sort transactions by date
usort($transactions, function($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
});

// Calculate running balance
$running_balance = 0;
foreach ($transactions as &$trans) {
    $running_balance += $trans['debit'] - $trans['credit'];
    $trans['balance'] = $running_balance;
}

// Filter by date range if specified
if ($date_from || $date_to) {
    $transactions = array_filter($transactions, function($trans) use ($date_from, $date_to) {
        $trans_date = strtotime($trans['date']);
        if ($date_from && $trans_date < strtotime($date_from)) return false;
        if ($date_to && $trans_date > strtotime($date_to)) return false;
        return true;
    });
}

// Include header
require_once dirname(__DIR__, 3) . '/views/partials/header.php';
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Statement: <?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('billing/dashboard.php'); ?>">Billing</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Debtors</a></li>
                    <li class="breadcrumb-item active">Statement</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Action Buttons -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="btn-group">
                    <a href="index.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left mr-1"></i> Back to Debtors
                    </a>
                    
                    <a href="<?php echo base_url('guests/view.php?id=' . $guest_id); ?>" class="btn btn-info">
                        <i class="fas fa-user mr-1"></i> View Guest
                    </a>
                    
                    <a href="../invoices/create.php?guest_id=<?php echo $guest_id; ?>" class="btn btn-success">
                        <i class="fas fa-plus-circle mr-1"></i> New Invoice
                    </a>
                    
                    <a href="../payments/add.php?guest_id=<?php echo $guest_id; ?>" class="btn btn-primary">
                        <i class="fas fa-dollar-sign mr-1"></i> Record Payment
                    </a>
                    
                    <button type="button" class="btn btn-warning" onclick="window.print()">
                        <i class="fas fa-print"></i> Print Statement
                    </button>
                    
                    <button type="button" class="btn btn-info" onclick="emailStatement()">
                        <i class="fas fa-envelope"></i> Email Statement
                    </button>
                </div>
            </div>
        </div>

        <!-- Guest Summary -->
        <div class="row">
            <div class="col-md-4">
                <div class="card card-primary card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user mr-1"></i>
                            Guest Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 100px;">Name:</th>
                                <td><?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td>
                                    <a href="mailto:<?php echo $guest['email']; ?>"><?php echo $guest['email']; ?></a>
                                </td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td>
                                    <?php if ($guest['phone']): ?>
                                        <a href="tel:<?php echo $guest['phone']; ?>"><?php echo $guest['phone']; ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Guest Code:</th>
                                <td><?php echo $guest['guest_code']; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card card-success card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar mr-1"></i>
                            Financial Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Total Invoiced:</th>
                                <td class="text-right"><?php echo format_currency($summary['total_invoiced']); ?></td>
                            </tr>
                            <tr>
                                <th>Total Paid:</th>
                                <td class="text-right text-success">- <?php echo format_currency($summary['total_paid']); ?></td>
                            </tr>
                            <tr class="table-active">
                                <th>Current Outstanding:</th>
                                <td class="text-right">
                                    <strong class="text-danger"><?php echo format_currency($summary['outstanding']); ?></strong>
                                </td>
                            </tr>
                            <?php if ($summary['overdue'] > 0): ?>
                            <tr>
                                <th>Overdue:</th>
                                <td class="text-right text-danger"><?php echo format_currency($summary['overdue']); ?></td>
                            </tr>
                            <?php endif; ?>
                            <tr>
                                <th>Invoices:</th>
                                <td class="text-right"><?php echo $summary['invoice_count']; ?></td>
                            </tr>
                            <tr>
                                <th>Payments:</th>
                                <td class="text-right"><?php echo $summary['payment_count']; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card card-info card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-filter mr-1"></i>
                            Date Range
                        </h3>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="form-inline">
                            <input type="hidden" name="guest_id" value="<?php echo $guest_id; ?>">
                            
                            <div class="form-group mb-2 mr-2">
                                <label for="date_from" class="mr-2">From:</label>
                                <input type="date" class="form-control" id="date_from" name="date_from" 
                                       value="<?php echo $date_from; ?>">
                            </div>
                            
                            <div class="form-group mb-2 mr-2">
                                <label for="date_to" class="mr-2">To:</label>
                                <input type="date" class="form-control" id="date_to" name="date_to" 
                                       value="<?php echo $date_to; ?>">
                            </div>
                            
                            <button type="submit" class="btn btn-sm btn-primary mb-2">
                                Apply
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Statement Transactions -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history mr-1"></i>
                            Account Statement
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($transactions)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-file-invoice fa-4x mb-3"></i>
                                <h5>No transactions found</h5>
                                <p>No invoices or payments recorded for this period</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Reference</th>
                                            <th>Description</th>
                                            <th class="text-right">Debit (Invoice)</th>
                                            <th class="text-right">Credit (Payment)</th>
                                            <th class="text-right">Balance</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $running_balance = 0;
                                        foreach ($transactions as $trans): 
                                            $running_balance = $trans['balance'];
                                        ?>
                                        <tr class="<?php 
                                            echo $trans['type'] == 'payment' ? 'table-success' : 
                                                ($trans['status'] == 'overdue' ? 'table-danger' : '');
                                        ?>">
                                            <td><?php echo format_date($trans['date']); ?></td>
                                            <td>
                                                <?php if ($trans['type'] == 'invoice'): ?>
                                                    <a href="../invoices/view.php?id=<?php echo $trans['reference']; ?>">
                                                        <?php echo $trans['reference']; ?>
                                                    </a>
                                                <?php else: ?>
                                                    <a href="../payments/view.php?id=<?php echo $trans['reference']; ?>">
                                                        <?php echo $trans['reference']; ?>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php echo $trans['description']; ?>
                                                <?php if ($trans['type'] == 'invoice' && $trans['status'] == 'overdue'): ?>
                                                    <span class="badge badge-danger">Overdue</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-right">
                                                <?php if ($trans['debit'] > 0): ?>
                                                    <?php echo format_currency($trans['debit']); ?>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-right">
                                                <?php if ($trans['credit'] > 0): ?>
                                                    <span class="text-success"><?php echo format_currency($trans['credit']); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-right">
                                                <strong><?php echo format_currency($running_balance); ?></strong>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr class="table-active">
                                            <th colspan="5" class="text-right">Final Balance:</th>
                                            <th class="text-right"><?php echo format_currency($running_balance); ?></th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Outstanding Invoices Detail -->
        <?php 
        $outstanding_invoices = array_filter($invoices, function($inv) {
            return $inv['balance'] > 0;
        });
        
        if (!empty($outstanding_invoices)): 
        ?>
        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exclamation-triangle mr-1"></i>
                            Outstanding Invoices
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Invoice #</th>
                                        <th>Date</th>
                                        <th>Due Date</th>
                                        <th class="text-right">Total</th>
                                        <th class="text-right">Paid</th>
                                        <th class="text-right">Balance</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($outstanding_invoices as $invoice): ?>
                                    <tr class="<?php echo $invoice['status'] == 'overdue' ? 'table-danger' : ''; ?>">
                                        <td>
                                            <a href="../invoices/view.php?id=<?php echo $invoice['invoice_id']; ?>">
                                                <?php echo $invoice['invoice_number']; ?>
                                            </a>
                                        </td>
                                        <td><?php echo format_date($invoice['invoice_date']); ?></td>
                                        <td>
                                            <?php echo format_date($invoice['due_date']); ?>
                                            <?php if ($invoice['days_overdue'] > 0): ?>
                                                <br>
                                                <small class="text-danger"><?php echo $invoice['days_overdue']; ?> days overdue</small>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-right"><?php echo format_currency($invoice['total_amount']); ?></td>
                                        <td class="text-right"><?php echo format_currency($invoice['paid_amount']); ?></td>
                                        <td class="text-right">
                                            <strong class="text-danger"><?php echo format_currency($invoice['balance']); ?></strong>
                                        </td>
                                        <td>
                                            <span class="badge badge-<?php 
                                                echo $invoice['status'] == 'overdue' ? 'danger' : 'warning';
                                            ?>">
                                                <?php echo ucfirst($invoice['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="../payments/add.php?invoice_id=<?php echo $invoice['invoice_id']; ?>" 
                                               class="btn btn-sm btn-success">
                                                <i class="fas fa-dollar-sign"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Email Statement Modal -->
<div class="modal fade" id="emailModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Email Statement</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form action="send-statement.php" method="POST">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="guest_id" value="<?php echo $guest_id; ?>">
                <input type="hidden" name="date_from" value="<?php echo $date_from; ?>">
                <input type="hidden" name="date_to" value="<?php echo $date_to; ?>">
                
                <div class="modal-body">
                    <p>Send statement to <strong><?php echo $guest['email']; ?></strong>?</p>
                    
                    <div class="form-group">
                        <label for="email_message">Additional Message</label>
                        <textarea class="form-control" id="email_message" name="message" rows="3"></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-info">Send Statement</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function emailStatement() {
    $('#emailModal').modal('show');
}
</script>

<style>
@media print {
    .main-header, .main-sidebar, .main-footer, .btn, .btn-group, .card-header .btn {
        display: none !important;
    }
    .content-wrapper {
        margin-left: 0 !important;
        padding: 0 !important;
    }
    .card {
        border: none !important;
        box-shadow: none !important;
    }
}
</style>

<?php
// Include footer
require_once dirname(__DIR__, 3) . '/views/partials/footer.php';
?>