<?php
// filename: petty_cash.php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'FINANCE_MANAGER'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$message = '';
$error = '';

// Handle advance/reimbursement (insert journal)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $amount = (float)$_POST['amount'];
    $description = trim($_POST['description'] ?? '');
    $petty_cash_account_id = (int)$_POST['petty_cash_account_id']; // Specific petty cash asset account
    $cash_account_id = (int)$_POST['cash_account_id'];
    
    if ($amount <= 0 || empty($description)) {
        $error = 'Invalid amount or description.';
    } else {
        $conn->begin_transaction();
        
        try {
            $today = date('Ymd');
            $max_sql = "SELECT COALESCE(MAX(CAST(SUBSTRING(journal_number, -4) AS UNSIGNED)), 0) + 1 as next_num 
                        FROM journal_entries WHERE journal_number LIKE 'PC-$today-%'";
            $max_result = $conn->query($max_sql);
            $next_num = $max_result->fetch_assoc()['next_num'];
            $journal_number = 'PC-' . $today . '-' . str_pad($next_num, 4, '0', STR_PAD_LEFT);
            
            $journal_sql = "INSERT INTO journal_entries (journal_number, entry_date, entry_type, description, status, created_by, created_at) 
                            VALUES (?, CURRENT_DATE, 'MANUAL', ?, 'POSTED', ?, CURRENT_TIMESTAMP)";
            $journal_stmt = $conn->prepare($journal_sql);
            $journal_stmt->bind_param('ssi', $journal_number, $description, $user_id);
            $journal_stmt->execute();
            $journal_id = $conn->insert_id;
            
            if ($action === 'advance') {
                // Debit petty cash, credit main cash
                $debit_sql = "INSERT INTO journal_entry_lines (journal_id, line_number, account_id, debit_amount, description) VALUES (?, 1, ?, ?, ?)";
                $debit_stmt = $conn->prepare($debit_sql);
                $debit_stmt->bind_param('iids', $journal_id, $petty_cash_account_id, $amount, $description);
                $debit_stmt->execute();
                
                $credit_sql = "INSERT INTO journal_entry_lines (journal_id, line_number, account_id, credit_amount, description) VALUES (?, 2, ?, ?, ?)";
                $credit_stmt = $conn->prepare($credit_sql);
                $credit_stmt->bind_param('iids', $journal_id, $cash_account_id, $amount, $description);
                $credit_stmt->execute();
            } else if ($action === 'reimburse') {
                // Debit expense (from receipt), credit petty cash
                $expense_account_id = (int)$_POST['expense_account_id'];
                $debit_sql = "INSERT INTO journal_entry_lines (journal_id, line_number, account_id, debit_amount, description) VALUES (?, 1, ?, ?, ?)";
                $debit_stmt = $conn->prepare($debit_sql);
                $debit_stmt->bind_param('iids', $journal_id, $expense_account_id, $amount, $description);
                $debit_stmt->execute();
                
                $credit_sql = "INSERT INTO journal_entry_lines (journal_id, line_number, account_id, credit_amount, description) VALUES (?, 2, ?, ?, ?)";
                $credit_stmt = $conn->prepare($credit_sql);
                $credit_stmt->bind_param('iids', $journal_id, $petty_cash_account_id, $amount, $description);
                $credit_stmt->execute();
            }
            
            // Update totals
            $update_sql = "UPDATE journal_entries SET total_debit = ?, total_credit = ? WHERE journal_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('ddi', $amount, $amount, $journal_id);
            $update_stmt->execute();
            
            $conn->commit();
            $message = ($action === 'advance' ? 'Advance' : 'Reimbursement') . ' recorded! Journal: ' . $journal_number;
            
            // Notification
            // PHPMailer/AfricasTalking here
            
        } catch (Exception $e) {
            $conn->rollback();
            $error = 'Failed: ' . $e->getMessage();
        }
    }
}

// Fetch petty cash balance (current_balance from chart_of_accounts where account_name like 'petty')
$petty_balance_sql = "SELECT current_balance FROM chart_of_accounts WHERE account_name LIKE '%petty%' AND account_type = 'ASSET' LIMIT 1";
$petty_balance_result = $conn->query($petty_balance_sql);
$petty_balance = $petty_balance_result ? $petty_balance_result->fetch_assoc()['current_balance'] ?? 0 : 0;

// Fetch cash accounts and expense categories (as in record_expense)
$cash_sql = "SELECT account_id, account_name FROM chart_of_accounts WHERE account_type = 'ASSET' AND (account_name LIKE '%cash%' OR account_name LIKE '%bank%') AND is_active = 1 ORDER BY account_name";
$cash_result = $conn->query($cash_sql);

$cat_sql = "SELECT account_id, account_name FROM chart_of_accounts WHERE account_type = 'EXPENSE' AND is_active = 1 ORDER BY account_name";
$cat_result = $conn->query($cat_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Petty Cash')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Petty Cash Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Petty Cash</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card expense-card">
                                <div class="card-header expense-header">
                                    <h5 class="mb-0 text-white"><i class="ri-money-dollar-circle-line me-2"></i>Petty Cash Balance</h5>
                                </div>
                                <div class="card-body text-center">
                                    <h3 class="text-danger">KES <?php echo number_format($petty_balance, 2); ?></h3>
                                    <p class="text-muted">Current Petty Cash Balance</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Advance Form -->
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="card expense-card">
                                <div class="card-header expense-header">
                                    <h6 class="mb-0 text-white"><i class="ri-arrow-down-line me-2"></i>Issue Advance</h6>
                                </div>
                                <div class="card-body">
                                    <?php if ($error && strpos($error, 'Advance') !== false): ?>
                                    <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                                    <?php endif; ?>
                                    
                                    <?php if (isset($message) && strpos($message, 'Advance') !== false): ?>
                                    <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
                                    <?php endif; ?>
                                    
                                    <form method="POST">
                                        <input type="hidden" name="action" value="advance">
                                        <div class="mb-3">
                                            <label class="form-label">Description <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="description" rows="2" placeholder="e.g., Petty cash advance for lab supplies" required></textarea>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Amount (KES) <span class="text-danger">*</span></label>
                                                <input type="number" step="0.01" class="form-control" name="amount" placeholder="0.00" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">From Account <span class="text-danger">*</span></label>
                                                <select class="form-select" name="cash_account_id" required>
                                                    <option value="">Select</option>
                                                    <?php while ($cash = $cash_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $cash['account_id']; ?>"><?php echo htmlspecialchars($cash['account_name']); ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-arrow-down-line me-1"></i>Issue Advance
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Reimbursement Form -->
                        <div class="col-lg-6">
                            <div class="card expense-card">
                                <div class="card-header expense-header">
                                    <h6 class="mb-0 text-white"><i class="ri-arrow-up-line me-2"></i>Reimburse Expense</h6>
                                </div>
                                <div class="card-body">
                                    <?php if ($error && strpos($error, 'Reimbursement') !== false): ?>
                                    <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                                    <?php endif; ?>
                                    
                                    <?php if (isset($message) && strpos($message, 'Reimbursement') !== false): ?>
                                    <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
                                    <?php endif; ?>
                                    
                                    <form method="POST">
                                        <input type="hidden" name="action" value="reimburse">
                                        <div class="mb-3">
                                            <label class="form-label">Description <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="description" rows="2" placeholder="e.g., Reimbursement for travel" required></textarea>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Amount (KES) <span class="text-danger">*</span></label>
                                                <input type="number" step="0.01" class="form-control" name="amount" placeholder="0.00" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Expense Category <span class="text-danger">*</span></label>
                                                <select class="form-select" name="expense_account_id" required>
                                                    <option value="">Select</option>
                                                    <?php $cat_result->data_seek(0); while ($cat = $cat_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $cat['account_id']; ?>"><?php echo htmlspecialchars($cat['account_name']); ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-arrow-up-line me-1"></i>Reimburse
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Transactions (journals with petty cash) -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card expense-card">
                                <div class="card-header expense-header">
                                    <h5 class="mb-0 text-white"><i class="ri-history-line me-2"></i>Recent Petty Cash Transactions</h5>
                                </div>
                                <div class="card-body p-0">
                                    <!-- Table of recent journals with petty cash accounts -->
                                    <div class="table-responsive">
                                        <table class="table table-sm mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Journal #</th>
                                                    <th>Date</th>
                                                    <th>Description</th>
                                                    <th>Amount</th>
                                                    <th>Type</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <!-- Query and loop recent journals involving petty cash account -->
                                                <?php
                                                $trans_sql = "SELECT je.journal_number, je.entry_date, je.description, je.status,
                                                                     SUM(CASE WHEN jel.account_id = ? THEN jel.debit_amount ELSE 0 END) - SUM(CASE WHEN jel.account_id = ? THEN jel.credit_amount ELSE 0 END) as net_amount
                                                              FROM journal_entries je
                                                              JOIN journal_entry_lines jel ON je.journal_id = jel.journal_id
                                                              WHERE jel.account_id = ?  -- Petty cash account ID (hardcode or fetch)
                                                              GROUP BY je.journal_id ORDER BY je.entry_date DESC LIMIT 10";
                                                // Assume petty_cash_account_id = 1; replace with actual
                                                $petty_id = 1; // Fetch from chart_of_accounts
                                                $trans_stmt = $conn->prepare($trans_sql);
                                                $trans_stmt->bind_param('iii', $petty_id, $petty_id, $petty_id);
                                                $trans_stmt->execute();
                                                $trans_result = $trans_stmt->get_result();
                                                while ($trans = $trans_result->fetch_assoc()): 
                                                ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($trans['journal_number']); ?></td>
                                                    <td><?php echo date('d M Y', strtotime($trans['entry_date'])); ?></td>
                                                    <td><?php echo htmlspecialchars($trans['description']); ?></td>
                                                    <td class="text-end"><?php echo number_format(abs($trans['net_amount']), 2); ?></td>
                                                    <td><?php echo $trans['net_amount'] > 0 ? 'Advance' : 'Reimbursement'; ?></td>
                                                    <td><span class="badge bg-<?php echo strtolower($trans['status']); ?>"><?php echo $trans['status']; ?></span></td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
</body>
</html>