<?php
// admin/accounts/deposits.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$account_filter = isset($_GET['account']) ? intval($_GET['account']) : 0;

// Get bank accounts for dropdown
$accounts = $pdo->query("SELECT id, account_name, account_number FROM bank_accounts WHERE status = 1 ORDER BY account_name")->fetchAll();

// Handle Add Deposit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_deposit'])) {
    $account_id = intval($_POST['account_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    $deposit_date = $_POST['deposit_date'] ?? date('Y-m-d');
    $payment_method = sanitize($_POST['payment_method'] ?? 'cash');
    $reference_no = sanitize($_POST['reference_no'] ?? '');
    $source = sanitize($_POST['source'] ?? '');
    $note = sanitize($_POST['note'] ?? '');

    if ($account_id > 0 && $amount > 0) {
        try {
            $deposit_no = 'DEP-' . date('Ymd') . '-' . rand(1000, 9999);

            // Insert deposit
            $stmt = $pdo->prepare("INSERT INTO deposits 
                (deposit_no, account_id, amount, deposit_date, payment_method, reference_no, source, note, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$deposit_no, $account_id, $amount, $deposit_date, $payment_method, $reference_no, $source, $note, $_SESSION['admin_id']]);

            // Update account balance
            $stmt = $pdo->prepare("UPDATE bank_accounts SET current_balance = current_balance + ? WHERE id = ?");
            $stmt->execute([$amount, $account_id]);

            // Add to transaction summary
            $stmt = $pdo->prepare("INSERT INTO account_transactions 
                (account_id, transaction_type, reference_no, amount, transaction_date, description, created_by) 
                VALUES (?, 'deposit', ?, ?, ?, ?, ?)");
            $stmt->execute([$account_id, $deposit_no, $amount, $deposit_date, $source ?: 'Deposit', $_SESSION['admin_id']]);

            $_SESSION['success_msg'] = 'Deposit added successfully!';
            header('Location: deposits.php');
            exit;
        } catch (Exception $e) {
            $_SESSION['error_msg'] = 'Error: ' . $e->getMessage();
        }
    }
}

// Get deposits
$sql = "SELECT d.*, b.account_name, b.account_number 
        FROM deposits d 
        LEFT JOIN bank_accounts b ON d.account_id = b.id";
if ($account_filter > 0) {
    $sql .= " WHERE d.account_id = " . $account_filter;
}
$sql .= " ORDER BY d.created_at DESC";

$deposits = $pdo->query($sql)->fetchAll();

// Get total deposits
$total_deposits = 0;
foreach ($deposits as $dep) {
    $total_deposits += $dep['amount'];
}

include '../header.php';
?>

<style>
.deposit-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-box {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.stat-box .stat-number {
    font-size: 24px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 13px;
    color: #64748b;
}

.deposit-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.filter-group {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
}

.filter-group .form-control {
    width: auto;
    min-width: 200px;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-arrow-down me-2"></i> Deposits</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#depositModal">
            <i class="fa-solid fa-plus"></i> Add Deposit
        </button>
    </div>

    <!-- Stats -->
    <div class="deposit-stats">
        <div class="stat-box">
            <div class="stat-number text-success"><?php echo count($deposits); ?></div>
            <div class="stat-label">Total Deposits</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-primary"><?php echo number_format($total_deposits); ?> TK</div>
            <div class="stat-label">Total Amount</div>
        </div>
    </div>

    <?php if ($_SESSION['success_msg'] ?? ''): ?>
    <div class="alert alert-success"><?php echo $_SESSION['success_msg']; unset($_SESSION['success_msg']); ?></div>
    <?php endif; ?>

    <!-- Filter -->
    <div class="deposit-card">
        <form method="GET" class="filter-group">
            <div>
                <label class="form-label mb-0">Account</label>
                <select name="account" class="form-control" onchange="this.form.submit()">
                    <option value="0">All Accounts</option>
                    <?php foreach ($accounts as $acc): ?>
                    <option value="<?php echo $acc['id']; ?>" <?php echo $account_filter == $acc['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($acc['account_name']); ?> (<?php echo $acc['account_number']; ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="form-label mb-0">&nbsp;</label>
                <a href="deposits.php" class="btn btn-secondary">Clear</a>
            </div>
        </form>
    </div>

    <div class="deposit-card">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Deposit No</th>
                        <th>Account</th>
                        <th>Amount</th>
                        <th>Method</th>
                        <th>Date</th>
                        <th>Source</th>
                        <th>Reference</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($deposits)): ?>
                    <tr><td colspan="8" class="text-center">No deposits found</td></tr>
                    <?php else: ?>
                    <?php foreach ($deposits as $dep): ?>
                    <tr>
                        <td><code><?php echo $dep['deposit_no']; ?></code></td>
                        <td><?php echo htmlspecialchars($dep['account_name'] ?? 'N/A'); ?></td>
                        <td class="text-success fw-bold"><?php echo number_format($dep['amount']); ?> TK</td>
                        <td><?php echo ucfirst($dep['payment_method']); ?></td>
                        <td><?php echo date('d M Y', strtotime($dep['deposit_date'])); ?></td>
                        <td><?php echo htmlspecialchars($dep['source'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($dep['reference_no'] ?? '-'); ?></td>
                        <td>
                            <button onclick="deleteDeposit(<?php echo $dep['id']; ?>)" class="btn btn-sm btn-danger">
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Deposit Modal -->
<div class="modal fade" id="depositModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Deposit</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="add_deposit" value="1">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Bank Account *</label>
                        <select name="account_id" class="form-control" required>
                            <option value="">Select Account</option>
                            <?php foreach ($accounts as $acc): ?>
                            <option value="<?php echo $acc['id']; ?>">
                                <?php echo htmlspecialchars($acc['account_name']); ?> (<?php echo $acc['account_number']; ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount *</label>
                        <input type="number" name="amount" class="form-control" step="0.01" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Deposit Date</label>
                        <input type="date" name="deposit_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Payment Method</label>
                        <select name="payment_method" class="form-control">
                            <option value="cash">Cash</option>
                            <option value="bank">Bank Transfer</option>
                            <option value="bkash">Bkash</option>
                            <option value="nagad">Nagad</option>
                            <option value="rocket">Rocket</option>
                            <option value="card">Card</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reference No</label>
                        <input type="text" name="reference_no" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Source</label>
                        <input type="text" name="source" class="form-control" placeholder="e.g. Sales, Invoice, etc.">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Deposit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function deleteDeposit(id) {
    if (confirm('Are you sure you want to delete this deposit?')) {
        window.location.href = 'delete-deposit.php?id=' + id;
    }
}
</script>

<?php include '../footer.php'; ?>