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

// Permission check
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Ensure fee_types table exists
try {
    // Create table if it doesn't exist
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS fee_types (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL UNIQUE,
            default_amount DECIMAL(10,2) NULL,
            status ENUM('active','inactive') DEFAULT 'active',
            sort_order INT DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");
    
    // Add description column if it doesn't exist
    try {
        $pdo->exec("ALTER TABLE fee_types ADD COLUMN description TEXT NULL");
    } catch (Exception $e) {
        // Column might already exist, ignore error
    }
} catch (Exception $e) {
    $error_message = 'টেবিল তৈরি করতে সমস্যা হয়েছে: ' . $e->getMessage();
}

// Handle add new fee type
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_type'])) {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $default_amount = trim($_POST['default_amount'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);

    if ($name === '') {
        $error_message = 'ফি টাইপের নাম প্রয়োজন।';
    } else {
        try {
            // Try to insert with description column
            try {
                $stmt = $pdo->prepare("INSERT INTO fee_types (name, description, default_amount, sort_order) VALUES (?, ?, ?, ?)");
                $val = ($default_amount === '' ? null : number_format((float)$default_amount, 2, '.', ''));
                $stmt->execute([$name, $description, $val, $sort_order]);
            } catch (Exception $e) {
                // If description column doesn't exist, insert without it
                $stmt = $pdo->prepare("INSERT INTO fee_types (name, default_amount, sort_order) VALUES (?, ?, ?)");
                $val = ($default_amount === '' ? null : number_format((float)$default_amount, 2, '.', ''));
                $stmt->execute([$name, $val, $sort_order]);
                
                // If successful, update the description if it exists now
                if ($description !== '') {
                    try {
                        $lastId = $pdo->lastInsertId();
                        $pdo->prepare("UPDATE fee_types SET description = ? WHERE id = ?")->execute([$description, $lastId]);
                    } catch (Exception $e) {
                        // Ignore if description column doesn't exist
                    }
                }
            }
            $success_message = 'নতুন ফি টাইপ যোগ হয়েছে।';
        } catch (Exception $e) {
            $error_message = 'ফি টাইপ যোগ করতে ব্যর্থ: ' . $e->getMessage();
        }
    }
}

// Handle update of existing type
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_type'])) {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $default_amount = trim($_POST['default_amount'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $status = ($_POST['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active';

    if ($id <= 0 || $name === '') {
        $error_message = 'সঠিক তথ্য প্রদান করুন।';
    } else {
        try {
            // Try to update with description column
            try {
                $stmt = $pdo->prepare("UPDATE fee_types SET name = ?, description = ?, default_amount = ?, sort_order = ?, status = ? WHERE id = ?");
                $val = ($default_amount === '' ? null : number_format((float)$default_amount, 2, '.', ''));
                $stmt->execute([$name, $description, $val, $sort_order, $status, $id]);
            } catch (Exception $e) {
                // If description column doesn't exist, update without it
                $stmt = $pdo->prepare("UPDATE fee_types SET name = ?, default_amount = ?, sort_order = ?, status = ? WHERE id = ?");
                $val = ($default_amount === '' ? null : number_format((float)$default_amount, 2, '.', ''));
                $stmt->execute([$name, $val, $sort_order, $status, $id]);
                
                // If successful, update the description if it exists now
                if ($description !== '') {
                    try {
                        $pdo->prepare("UPDATE fee_types SET description = ? WHERE id = ?")->execute([$description, $id]);
                    } catch (Exception $e) {
                        // Ignore if description column doesn't exist
                    }
                }
            }
            $success_message = 'ফি টাইপ আপডেট হয়েছে।';
        } catch (Exception $e) {
            $error_message = 'আপডেট করতে ব্যর্থ: ' . $e->getMessage();
        }
    }
}

// Handle toggle status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_status'])) {
    $id = (int)($_POST['id'] ?? 0);
    $to = ($_POST['to'] ?? 'active') === 'inactive' ? 'inactive' : 'active';
    if ($id > 0) {
        try {
            $stmt = $pdo->prepare("UPDATE fee_types SET status = ? WHERE id = ?");
            $stmt->execute([$to, $id]);
            $success_message = 'স্ট্যাটাস পরিবর্তন হয়েছে।';
        } catch (Exception $e) {
            $error_message = 'স্ট্যাটাস পরিবর্তনে সমস্যা: ' . $e->getMessage();
        }
    }
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_type'])) {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        try {
            // Check if fee type is being used in fees table
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM fees WHERE fee_type_id = ?");
            $stmt->execute([$id]);
            $count = $stmt->fetchColumn();
            
            if ($count > 0) {
                $error_message = 'এই ফি টাইপ ব্যবহার হচ্ছে, মুছে ফেলা যাবে না।';
            } else {
                $stmt = $pdo->prepare("DELETE FROM fee_types WHERE id = ?");
                $stmt->execute([$id]);
                $success_message = 'ফি টাইপ মুছে ফেলা হয়েছে।';
            }
        } catch (Exception $e) {
            $error_message = 'ডিলেট করতে সমস্যা: ' . $e->getMessage();
        }
    }
}

// Load types
try {
    // Try to select with description column
    $stmt = $pdo->query("SELECT id, name, description, default_amount, status, sort_order, created_at FROM fee_types ORDER BY sort_order, name");
} catch (Exception $e) {
    // If description column doesn't exist, select without it
    $stmt = $pdo->query("SELECT id, name, default_amount, status, sort_order, created_at FROM fee_types ORDER BY sort_order, name");
}
$types = $stmt->fetchAll();

// Add empty description field if it doesn't exist in the result
if (!empty($types) && !isset($types[0]['description'])) {
    foreach ($types as &$type) {
        $type['description'] = '';
    }
}
?>
<!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">
    <style>
        body { font-family: 'Hind Siliguri', sans-serif; }
        .form-control, .form-select { font-size: 0.9rem; }
        .form-control-sm, .form-select-sm { font-size: 0.85rem; }
        .table th { background-color: #e8f5e9; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.8rem; }
        .description-cell { max-width: 250px; }
        .description-cell textarea { font-size: 0.85rem; height: auto; min-height: 30px; resize: vertical; }
        .card-body { padding: 1rem; }
        .card-header { padding: 0.75rem 1rem; font-size: 1rem; }
        .btn-group .btn { margin: 0 2px; }
        .action-cell { white-space: nowrap; }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="manage.php">
            <i class="fas fa-money-bill"></i> ফি ম্যানেজমেন্ট
        </a>
        <div class="navbar-nav ms-auto">
            <a class="nav-link" href="manage.php"><i class="fas fa-arrow-left"></i> ফিরে যান</a>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-md-4">
            <div class="card">
                <div class="card-header"><strong><i class="fas fa-plus-circle"></i> নতুন ফি টাইপ যোগ</strong></div>
                <div class="card-body">
                    <form method="post">
                        <div class="mb-2">
                            <label class="form-label mb-1">নাম <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control form-control-sm" required placeholder="যেমন: মাসিক বেতন">
                        </div>
                        <div class="mb-2">
                            <label class="form-label mb-1">বিবরণ (ঐচ্ছিক)</label>
                            <textarea name="description" class="form-control form-control-sm" rows="2" placeholder="ফি টাইপের বিস্তারিত বিবরণ" style="font-size: 0.85rem;"></textarea>
                        </div>
                        <div class="mb-2">
                            <label class="form-label mb-1">ডিফল্ট পরিমাণ</label>
                            <input type="number" name="default_amount" class="form-control form-control-sm" step="0.01" min="0" placeholder="যেমন: 500.00">
                        </div>
                        <div class="mb-3">
                            <label class="form-label mb-1">সোর্ট অর্ডার</label>
                            <input type="number" name="sort_order" class="form-control form-control-sm" step="1" min="0" value="0">
                        </div>
                        <button type="submit" name="add_type" class="btn btn-primary btn-sm w-100">
                            <i class="fas fa-save"></i> যোগ করুন
                        </button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <strong><i class="fas fa-list"></i> ফি টাইপ লিস্ট</strong>
                    <a href="manage.php" class="btn btn-sm btn-outline-primary"><i class="fas fa-money-bill"></i> ফি নির্ধারণ</a>
                </div>
                <div class="card-body">
                    <?php if (empty($types)): ?>
                        <p class="text-muted">কোন ফি টাইপ নেই। আগে একটি যোগ করুন।</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped align-middle">
                                <thead>
                                    <tr>
                                        <th>নাম</th>
                                        <th>বিবরণ</th>
                                        <th>ডিফল্ট পরিমাণ</th>
                                        <th>অবস্থা</th>
                                        <th>সোর্ট</th>
                                        <th class="text-center">একশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($types as $t): ?>
                                    <tr>
                                        <form method="post">
                                            <input type="hidden" name="id" value="<?php echo (int)$t['id']; ?>">
                                            <td>
                                                <input type="text" name="name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($t['name']); ?>" required disabled>
                                            </td>
                                            <td class="description-cell">
                                                <textarea name="description" class="form-control form-control-sm" rows="1" placeholder="বিবরণ" disabled style="height: auto; min-height: 30px; resize: vertical;"><?php echo htmlspecialchars($t['description'] ?? ''); ?></textarea>
                                            </td>
                                            <td style="max-width: 140px;">
                                                <div class="input-group input-group-sm">
                                                    <span class="input-group-text">৳</span>
                                                    <input type="number" name="default_amount" class="form-control" step="0.01" min="0" value="<?php echo htmlspecialchars($t['default_amount']); ?>" disabled>
                                                </div>
                                            </td>
                                            <td>
                                                <select name="status" class="form-select form-select-sm" disabled>
                                                    <option value="active" <?php echo $t['status']==='active'?'selected':''; ?>>সক্রিয়</option>
                                                    <option value="inactive" <?php echo $t['status']==='inactive'?'selected':''; ?>>নিষ্ক্রিয়</option>
                                                </select>
                                            </td>
                                            <td style="max-width: 90px;">
                                                <input type="number" name="sort_order" class="form-control form-control-sm" step="1" min="0" value="<?php echo (int)$t['sort_order']; ?>" disabled>
                                            </td>
                                            <td class="text-center action-cell">
                                                <div class="btn-group btn-group-sm" role="group">
                                                    <button type="submit" name="update_type" class="btn btn-success" title="সেভ">
                                                        <i class="fas fa-save"></i>
                                                    </button>
                                                    <?php if ($t['status'] === 'active'): ?>
                                                        <button type="submit" name="toggle_status" value="1" class="btn btn-warning" title="ইনঅ্যাক্টিভ" formaction="" formmethod="post" onclick="this.form.to.value='inactive'">
                                                            <i class="fas fa-ban"></i>
                                                        </button>
                                                    <?php else: ?>
                                                        <button type="submit" name="toggle_status" value="1" class="btn btn-primary" title="অ্যাক্টিভ" formaction="" formmethod="post" onclick="this.form.to.value='active'">
                                                            <i class="fas fa-check"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    <button type="button" class="btn btn-info edit-btn" title="এডিট" onclick="enableEdit(this)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-danger" title="ডিলেট" onclick="confirmDelete(<?php echo (int)$t['id']; ?>, '<?php echo htmlspecialchars($t['name']); ?>')">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                                <input type="hidden" name="to" value="<?php echo $t['status'] === 'active' ? 'inactive' : 'active'; ?>">
                                            </td>
                                        </form>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function enableEdit(button) {
        // Find the closest row
        const row = button.closest('tr');
        
        // Enable all input fields in this row
        const inputs = row.querySelectorAll('input, textarea, select');
        inputs.forEach(input => {
            input.disabled = false;
        });
        
        // Change button to save icon
        button.innerHTML = '<i class="fas fa-save"></i>';
        button.title = 'সেভ';
        button.className = 'btn btn-success edit-btn';
        
        // Change the button's onclick function
        button.onclick = function() {
            // Submit the form
            row.querySelector('form').submit();
        };
    }
    
    function confirmDelete(id, name) {
        if (confirm('আপনি কি নিশ্চিতভাবে \'' + name + '\' ফি টাইপ মুছে ফেলতে চান?')) {
            // Create a form to submit the delete request
            const form = document.createElement('form');
            form.method = 'post';
            form.style.display = 'none';
            
            const idInput = document.createElement('input');
            idInput.type = 'hidden';
            idInput.name = 'id';
            idInput.value = id;
            
            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'delete_type';
            actionInput.value = '1';
            
            form.appendChild(idInput);
            form.appendChild(actionInput);
            document.body.appendChild(form);
            form.submit();
        }
    }
</script>
</body>
</html>