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

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

// Handle Add Income
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_income'])) {
    $customer_name = sanitize($_POST['customer_name'] ?? '');
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method = sanitize($_POST['payment_method'] ?? 'cash');
    $reference_no = sanitize($_POST['reference_no'] ?? '');
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
    $note = sanitize($_POST['note'] ?? '');
    $invoice_id = isset($_POST['invoice_id']) && !empty($_POST['invoice_id']) ? intval($_POST['invoice_id']) : null;
    $order_id = isset($_POST['order_id']) && !empty($_POST['order_id']) ? intval($_POST['order_id']) : null;
    
    if ($customer_name && $amount > 0) {
        $income_no = 'INC-' . date('Ymd') . '-' . rand(1000, 9999);
        $stmt = $pdo->prepare("INSERT INTO income 
            (income_no, invoice_id, order_id, customer_name, amount, payment_method, reference_no, payment_date, note, received_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$income_no, $invoice_id, $order_id, $customer_name, $amount, 
                        $payment_method, $reference_no, $payment_date, $note, $_SESSION['user_id']]);
        
        // Update invoice paid amount if linked
        if ($invoice_id) {
            $stmt = $pdo->prepare("UPDATE invoices SET paid_amount = paid_amount + ?, due_amount = total - paid_amount WHERE id = ?");
            $stmt->execute([$amount, $invoice_id]);
            
            // Update invoice status
            $stmt = $pdo->prepare("SELECT total, paid_amount FROM invoices WHERE id = ?");
            $stmt->execute([$invoice_id]);
            $invoice = $stmt->fetch();
            if ($invoice['paid_amount'] >= $invoice['total']) {
                $stmt = $pdo->prepare("UPDATE invoices SET status = 'paid' WHERE id = ?");
                $stmt->execute([$invoice_id]);
            } elseif ($invoice['paid_amount'] > 0) {
                $stmt = $pdo->prepare("UPDATE invoices SET status = 'partial' WHERE id = ?");
                $stmt->execute([$invoice_id]);
            }
        }
        
        $_SESSION['success_msg'] = 'Income added successfully!';
        header('Location: income.php');
        exit;
    }
}

// Get income records
$stmt = $pdo->query("SELECT * FROM income ORDER BY created_at DESC");
$incomes = $stmt->fetchAll();

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

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

<style>
.account-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.account-nav a {
    padding: 8px 20px;
    border-radius: 8px;
    color: #64748b;
    text-decoration: none;
    transition: all 0.3s ease;
}

.account-nav a:hover,
.account-nav a.active {
    background: #047dc3;
    color: #fff;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Income (Payment Received)</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#incomeModal">
            <i class="fa-solid fa-plus"></i> Add Income
        </button>
    </div>
    
    <!-- Navigation -->
    <div class="account-nav">
        <a href="dashboard.php"><i class="fa-solid fa-chart-pie"></i> Dashboard</a>
        <a href="income.php" class="active"><i class="fa-solid fa-arrow-down"></i> Income</a>
        <a href="expenses.php"><i class="fa-solid fa-arrow-up"></i> Expenses</a>
        <a href="invoices.php"><i class="fa-solid fa-file-invoice"></i> Invoices</a>
        <a href="purchase-orders.php"><i class="fa-solid fa-file-purchase"></i> Purchase Orders</a>
        <a href="vendors.php"><i class="fa-solid fa-building"></i> Vendors</a>
        <a href="po-payments.php"><i class="fa-solid fa-hand-holding-dollar"></i> PO Payments</a>
        <a href="reports.php"><i class="fa-solid fa-chart-bar"></i> Reports</a>
    </div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>
    
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Income No</th>
                            <th>Customer</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Date</th>
                            <th>Reference</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($incomes)): ?>
                        <tr><td colspan="7" class="text-center">No income records</td></tr>
                        <?php else: ?>
                        <?php foreach ($incomes as $income): ?>
                        <tr>
                            <td><code><?php echo $income['income_no']; ?></code></td>
                            <td><?php echo $income['customer_name']; ?></td>
                            <td class="text-success"><?php echo number_format($income['amount']); ?> TK</td>
                            <td><?php echo ucfirst($income['payment_method']); ?></td>
                            <td><?php echo date('d M Y', strtotime($income['payment_date'])); ?></td>
                            <td><?php echo $income['reference_no'] ?? '-'; ?></td>
                            <td>
                                <button class="btn btn-sm btn-danger" onclick="deleteIncome(<?php echo $income['id']; ?>)">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Income Modal -->
<div class="modal fade" id="incomeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Income</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="add_income" value="1">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Customer Name *</label>
                        <input type="text" name="customer_name" class="form-control" required>
                    </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">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">Payment Date</label>
                        <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                    </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</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function deleteIncome(id) {
    if (confirm('Delete this income record?')) {
        fetch('delete-income.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) location.reload();
        });
    }
}
</script>

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