<?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_category'])) {
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);
        
        if (empty($name)) {
            $error = 'বিয়োগ বিভাগের নাম প্রয়োজন';
        } else {
            $stmt = $pdo->prepare("INSERT INTO expense_categories (name, description, status) VALUES (?, ?, 'active')");
            if ($stmt->execute([$name, $description])) {
                $message = 'বিয়োগ বিভাগ সফলভাবে যোগ করা হয়েছে';
            } else {
                $error = 'বিয়োগ বিভাগ যোগ করতে ত্রুটি হয়েছে';
            }
        }
    }
    
    if (isset($_POST['edit_category'])) {
        $id = $_POST['id'];
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);
        $status = $_POST['status'];
        
        if (empty($name)) {
            $error = 'বিয়োগ বিভাগের নাম প্রয়োজন';
        } else {
            $stmt = $pdo->prepare("UPDATE expense_categories SET name=?, description=?, status=? WHERE id=?");
            if ($stmt->execute([$name, $description, $status, $id])) {
                $message = 'বিয়োগ বিভাগ সফলভাবে আপডেট করা হয়েছে';
            } else {
                $error = 'বিয়োগ বিভাগ আপডেট করতে ত্রুটি হয়েছে';
            }
        }
    }
    
    if (isset($_POST['delete_category'])) {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM expense_categories WHERE id=?");
        if ($stmt->execute([$id])) {
            $message = 'বিয়োগ বিভাগ সফলভাবে মুছে ফেলা হয়েছে';
        } else {
            $error = 'বিয়োগ বিভাগ মুছতে ত্রুটি হয়েছে';
        }
    }
}

// Fetch all expense categories
$stmt = $pdo->query("SELECT * FROM expense_categories ORDER BY name ASC");
$categories = $stmt->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;
        }
        
        .status-active {
            color: #28a745;
            font-weight: bold;
        }
        
        .status-inactive {
            color: #dc3545;
            font-weight: bold;
        }
        
        /* 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-list"></i> বিয়োগ বিভাগ তালিকা</h5>
                        <span class="badge bg-primary"><?php echo count($categories); ?> টি বিভাগ</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>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($categories as $index => $category): ?>
                                    <tr>
                                        <td><?php echo $index + 1; ?></td>
                                        <td><?php echo htmlspecialchars($category['name']); ?></td>
                                        <td><?php echo htmlspecialchars($category['description'] ?? ''); ?></td>
                                        <td>
                                            <span class="<?php echo $category['status'] === 'active' ? 'status-active' : 'status-inactive'; ?>">
                                                <?php echo $category['status'] === 'active' ? 'সক্রিয়' : 'নিষ্ক্রিয়'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary" onclick="editCategory(<?php echo $category['id']; ?>, '<?php echo addslashes($category['name']); ?>', '<?php echo addslashes($category['description'] ?? ''); ?>', '<?php echo $category['status']; ?>')" 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 $category['id']; ?>">
                                                <button type="submit" name="delete_category" class="btn btn-sm btn-outline-danger" title="মুছুন">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($categories)): ?>
                                    <tr>
                                        <td colspan="5" 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>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">বর্ণনা</label>
                                <textarea class="form-control" name="description" rows="3"></textarea>
                            </div>
                            <button type="submit" name="add_category" 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">
            <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="mb-3">
                            <label class="form-label">বিভাগের নাম *</label>
                            <input type="text" class="form-control" name="name" id="edit_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">বর্ণনা</label>
                            <textarea class="form-control" name="description" id="edit_description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">অবস্থা</label>
                            <select class="form-control" name="status" id="edit_status">
                                <option value="active">সক্রিয়</option>
                                <option value="inactive">নিষ্ক্রিয়</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" name="edit_category" 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 editCategory(id, name, description, status) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_description').value = description;
            document.getElementById('edit_status').value = status;
            new bootstrap.Modal(document.getElementById('editModal')).show();
        }
    </script>
</body>
</html>
