<?php
session_start();
require_once '../config/database.php';
require_once '../includes/sidebar_layout.php';

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

// Handle form submissions
$message = '';
$error = '';

// Get user information for sidebar
$user_role = $_SESSION['user_role'] ?? 'admin';
$user_name = $_SESSION['user_name'] ?? $_SESSION['username'] ?? 'User';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_expense'])) {
        $category_id = $_POST['category_id'];
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);
        $amount = $_POST['amount'];
        $expense_date = $_POST['expense_date'];
        $payment_method = $_POST['payment_method'];
        $receipt_no = trim($_POST['receipt_no']);
        
        if (empty($title) || empty($amount) || empty($expense_date)) {
            $error = 'সমস্ত প্রয়োজনীয় তথ্য পূরণ করুন';
        } else {
            $stmt = $pdo->prepare("INSERT INTO expenses (category_id, title, description, amount, expense_date, payment_method, receipt_no, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            if ($stmt->execute([$category_id, $title, $description, $amount, $expense_date, $payment_method, $receipt_no, $_SESSION['user_id']])) {
                $message = 'বিয়োগ সফলভাবে যোগ করা হয়েছে';
            } else {
                $error = 'বিয়োগ যোগ করতে ত্রুটি হয়েছে';
            }
        }
    }
    
    if (isset($_POST['edit_expense'])) {
        $id = $_POST['id'];
        $category_id = $_POST['category_id'];
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);
        $amount = $_POST['amount'];
        $expense_date = $_POST['expense_date'];
        $payment_method = $_POST['payment_method'];
        $receipt_no = trim($_POST['receipt_no']);
        
        if (empty($title) || empty($amount) || empty($expense_date)) {
            $error = 'সমস্ত প্রয়োজনীয় তথ্য পূরণ করুন';
        } else {
            $stmt = $pdo->prepare("UPDATE expenses SET category_id=?, title=?, description=?, amount=?, expense_date=?, payment_method=?, receipt_no=? WHERE id=?");
            if ($stmt->execute([$category_id, $title, $description, $amount, $expense_date, $payment_method, $receipt_no, $id])) {
                $message = 'বিয়োগ সফলভাবে আপডেট করা হয়েছে';
            } else {
                $error = 'বিয়োগ আপডেট করতে ত্রুটি হয়েছে';
            }
        }
    }
    
    if (isset($_POST['delete_expense'])) {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM expenses WHERE id=?");
        if ($stmt->execute([$id])) {
            $message = 'বিয়োগ সফলভাবে মুছে ফেলা হয়েছে';
        } else {
            $error = 'বিয়োগ মুছতে ত্রুটি হয়েছে';
        }
    }
}

// Fetch all expenses with category names
try {
    $stmt = $pdo->query("
        SELECT e.*, ec.name as category_name, u.username as created_by_name 
        FROM expenses e 
        LEFT JOIN expense_categories ec ON e.category_id = ec.id 
        LEFT JOIN users u ON e.created_by = u.id 
        ORDER BY e.expense_date DESC, e.id DESC
    ");
    $expenses = $stmt->fetchAll();
} catch (Exception $e) {
    // Fallback query if created_by column doesn't exist or has issues
    $stmt = $pdo->query("
        SELECT e.*, ec.name as category_name
        FROM expenses e 
        LEFT JOIN expense_categories ec ON e.category_id = ec.id 
        ORDER BY e.expense_date DESC, e.id DESC
    ");
    $expenses = $stmt->fetchAll();
    // Add empty created_by_name for compatibility
    foreach ($expenses as &$expense) {
        $expense['created_by_name'] = '';
    }
}

// Fetch all expense categories for dropdown
$categoryStmt = $pdo->query("SELECT * FROM expense_categories WHERE status = 'active' ORDER BY name ASC");
$categories = $categoryStmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>বিয়োগ পরিচালনা - বিদ্যা সংগঠন</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f4f7f6;
            direction: rtl;
            margin: 0;
            padding: 0;
        }
        
        /* Override text direction for form elements to be left-to-right */
        .form-label, .form-control, .form-select, textarea {
            direction: ltr;
            text-align: left;
        }
        
        /* Ensure form labels are properly aligned */
        .mb-3 {
            direction: ltr;
        }
        
        .navbar {
            background: linear-gradient(135deg, #d32f2f 0%, #c62828 100%);
        }
        
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
        }
        
        .table th {
            background-color: #d32f2f;
            color: white;
        }
        
        .btn-primary {
            background-color: #d32f2f;
            border-color: #d32f2f;
        }
        
        .btn-primary:hover {
            background-color: #c62828;
            border-color: #c62828;
        }
        
        .amount-text {
            font-weight: bold;
            color: #dc3545;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #d32f2f;
            box-shadow: 0 0 0 0.2rem rgba(211, 47, 47, 0.25);
        }
        
        /* Add proper spacing for full-width content */
        .container-fluid {
            padding-left: 20px;
            padding-right: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <!-- Navigation Buttons -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <a href="javascript:history.back()" class="btn btn-outline-secondary me-2">
                            <i class="fas fa-arrow-left"></i> Back
                        </a>
                        <a href="../index.php" class="btn btn-outline-success">
                            <i class="fas fa-home"></i> Home Page
                        </a>
                    </div>
                    <h2 class="mb-0">বিয়োগ পরিচালনা</h2>
                </div>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-receipt"></i> বিয়োগ তালিকা</h5>
                        <span class="badge bg-primary"><?php echo count($expenses); ?> টি বিয়োগ</span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>বিভাগ</th>
                                        <th>শিরোনাম</th>
                                        <th>পরিমাণ (৳)</th>
                                        <th>পদ্ধতি</th>
                                        <th>কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($expenses as $expense): ?>
                                    <tr>
                                        <td><?php echo date('d/m/Y', strtotime($expense['expense_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($expense['category_name']); ?></td>
                                        <td><?php echo htmlspecialchars($expense['title']); ?></td>
                                        <td class="amount-text">৳<?php echo number_format($expense['amount'], 2); ?></td>
                                        <td><?php echo $expense['payment_method'] == 'cash' ? 'নগদ' : ($expense['payment_method'] == 'bank_transfer' ? 'ব্যাংক ট্রান্সফার' : ($expense['payment_method'] == 'mobile_banking' ? 'মোবাইল ব্যাংকিং' : 'চেক')); ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary" onclick="editExpense(<?php echo $expense['id']; ?>, <?php echo $expense['category_id']; ?>, '<?php echo addslashes($expense['title']); ?>', '<?php echo addslashes($expense['description'] ?? ''); ?>', <?php echo $expense['amount']; ?>, '<?php echo $expense['expense_date']; ?>', '<?php echo $expense['payment_method']; ?>', '<?php echo addslashes($expense['receipt_no'] ?? ''); ?>')" title="সম্পাদনা">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিত?')">
                                                <input type="hidden" name="id" value="<?php echo $expense['id']; ?>">
                                                <button type="submit" name="delete_expense" class="btn btn-sm btn-outline-danger" title="মুছুন">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($expenses)): ?>
                                    <tr>
                                        <td colspan="6" class="text-center">কোন বিয়োগ পাওয়া যায়নি</td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-plus-circle"></i> নতুন বিয়োগ</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">বিয়োগ বিভাগ *</label>
                                <select class="form-select" name="category_id" required>
                                    <option value="">বিভাগ নির্বাচন করুন</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">শিরোনাম *</label>
                                <input type="text" class="form-control" name="title" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">বর্ণনা</label>
                                <textarea class="form-control" name="description" rows="2"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">পরিমাণ (৳) *</label>
                                <input type="number" class="form-control" name="amount" step="0.01" min="0" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">তারিখ *</label>
                                <input type="date" class="form-control" name="expense_date" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">পরিশোধের পদ্ধতি</label>
                                <select class="form-select" name="payment_method">
                                    <option value="cash">নগদ</option>
                                    <option value="bank_transfer">ব্যাংক ট্রান্সফার</option>
                                    <option value="mobile_banking">মোবাইল ব্যাংকিং</option>
                                    <option value="check">চেক</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">রশিদ নম্বর</label>
                                <input type="text" class="form-control" name="receipt_no">
                            </div>
                            <button type="submit" name="add_expense" class="btn btn-primary w-100">
                                <i class="fas fa-save"></i> বিয়োগ যোগ করুন
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">বিয়োগ সম্পাদনা</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="id" id="edit_id">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">বিয়োগ বিভাগ *</label>
                                    <select class="form-select" name="category_id" id="edit_category_id" required>
                                        <option value="">বিভাগ নির্বাচন করুন</option>
                                        <?php foreach ($categories as $category): ?>
                                            <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">পরিমাণ (৳) *</label>
                                    <input type="number" class="form-control" name="amount" id="edit_amount" step="0.01" min="0" required>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">শিরোনাম *</label>
                            <input type="text" class="form-control" name="title" id="edit_title" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">বর্ণনা</label>
                            <textarea class="form-control" name="description" id="edit_description" rows="2"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">তারিখ *</label>
                                    <input type="date" class="form-control" name="expense_date" id="edit_expense_date" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">পরিশোধের পদ্ধতি</label>
                                    <select class="form-select" name="payment_method" id="edit_payment_method">
                                        <option value="cash">নগদ</option>
                                        <option value="bank_transfer">ব্যাংক ট্রান্সফার</option>
                                        <option value="mobile_banking">মোবাইল ব্যাংকিং</option>
                                        <option value="check">চেক</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রশিদ নম্বর</label>
                            <input type="text" class="form-control" name="receipt_no" id="edit_receipt_no">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" name="edit_expense" class="btn btn-primary">হালনাগাদ</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function editExpense(id, categoryId, title, description, amount, date, paymentMethod, receiptNo) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_category_id').value = categoryId;
            document.getElementById('edit_title').value = title;
            document.getElementById('edit_description').value = description;
            document.getElementById('edit_amount').value = amount;
            document.getElementById('edit_expense_date').value = date;
            document.getElementById('edit_payment_method').value = paymentMethod;
            document.getElementById('edit_receipt_no').value = receiptNo;
            new bootstrap.Modal(document.getElementById('editModal')).show();
        }
    </script>
</body>
</html>