<?php
// Add fee structure
// === ENABLE ERROR REPORTING ===
error_reporting(E_ALL);
ini_set('display_errors', 1);

// === ADD FEE STRUCTURE ===
if (isset($_POST['add_fee_structure'])) {
    $class = $_POST['class'] ?? '';
    $term = $_POST['term'] ?? '';
    $sessionVal = $_POST['session'] ?? '';
    $amount = $_POST['amount'] ?? 0;

    if ($class && $term && $sessionVal && $amount > 0) {
        // === CHECK IF SAME RECORD ALREADY EXISTS ===
        $check = $connection->prepare("SELECT COUNT(*) AS total FROM fee_structure WHERE class = ? AND term = ? AND session = ?");
        $check->bind_param("sss", $class, $term, $sessionVal);
        $check->execute();
        $result = $check->get_result();
        $row = $result->fetch_assoc();

        if ($row['total'] > 0) {
            // Record already exists
            $_SESSION['msg'] = "Fee structure for this Class, Term, and Session already exists.";
            $_SESSION['type'] = "warning";
        } else {
            // === INSERT NEW RECORD ===
            $stmt = $connection->prepare("INSERT INTO fee_structure (class, term, session, amount) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("sssd", $class, $term, $sessionVal, $amount);
            $stmt->execute();

            $_SESSION['msg'] = "Fee structure added successfully.";
            $_SESSION['type'] = "success";
        }
    } else {
        $_SESSION['msg'] = "All fields are required.";
        $_SESSION['type'] = "danger";
    }

    header("Location: fee_structure");
    exit;
}


// Edit fee structure
if (isset($_POST['edit_fee_structure'])) {
    $id = $_POST['id'];
    $class = $_POST['class'];
    $term = $_POST['term'];
    $sessionVal = $_POST['session'];
    $amount = $_POST['amount'];

    $stmt = $connection->prepare("UPDATE fee_structure SET class=?, term=?, session=?, amount=? WHERE id=?");
    $stmt->bind_param("sssdi", $class, $term, $sessionVal, $amount, $id);
    $stmt->execute();
    $_SESSION['msg'] = "Fee structure updated.";
    $_SESSION['type'] = "info";
    header("Location: fee_structure");
    exit;
}

// Delete fee structure
if (isset($_POST['delete_fee_structure'])) {
    $id = $_POST['id'];
    $stmt = $connection->prepare("DELETE FROM fee_structure WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $_SESSION['msg'] = "Fee structure deleted.";
    $_SESSION['type'] = "danger";
    header("Location: fee_structure");
    exit;
}
?>


<div class="page-title">
    <h1><i class="fa fa-money"></i> Add Fee Structure</h1>
</div>

<div class="card">
    <div class="panel panel-primary">
        <div class="panel-heading">Define Fee for a Class by Term and Session</div>
        <div class="panel-body">
            <form method="POST">
                <div class="row">
                    <div class="col-md-3">
                       <select class='form-control' name='class'>
                                <option disabled selected>Select Class</option>
                                    <?php
                                        $query = " SELECT * FROM `classes` ";
                                        $run_query = mysqli_query($connection, $query);
                                        if(mysqli_num_rows($run_query) > 0){
                                            while($result = mysqli_fetch_assoc($run_query)){
                                                $classes = $result['classes'];
                                                echo"
                                                    <option>{$classes}</option>
                                                ";
                                            }
                                        }
                                    ?>
                            </select>
                    </div>
                    <div class="col-md-2">
                        <select name="term" class="form-control" required>
                            <option disabled selected>Select Term</option>
                            <option>First Term</option>
                            <option>Second Term</option>
                            <option>Third Term</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select name="session" class="form-control" required>
                            <option disabled selected>Select Session</option>
                            <?php
                            $get = $connection->query("SELECT sessions FROM sessions");
                            while ($row = $get->fetch_assoc()) {
                                echo "<option>{$row['sessions']}</option>";
                            }
                            ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <input type="number" step="0.01" name="amount" class="form-control" placeholder="₦ Amount" required>
                    </div>
                </div>
                <br>
                <button name="add_fee_structure" class="btn btn-primary">Add Fee Structure</button>
            </form>
        </div>
    </div>
</div>

<!-- Fee Structure Table -->
<hr>
<div class="card">
    <div class="panel panel-info">
        <div class="panel-heading">Fee Structure List</div>
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table">
                    <thead class="bg-primary text-white">
                        <tr>
                            <th>#</th>
                            <th>Class</th>
                            <th>Term</th>
                            <th>Session</th>
                            <th>Amount (₦)</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $query = $connection->query("SELECT * FROM fee_structure ORDER BY id DESC");
                        $i = 0;
                        while ($row = $query->fetch_assoc()):
                            $i++;
                        ?>
                            <tr>
                                <td><?= $i ?></td>
                                <td><?= htmlspecialchars($row['class']) ?></td>
                                <td><?= $row['term'] ?></td>
                                <td><?= $row['session'] ?></td>
                                <td><strong>₦<?= number_format($row['amount'], 2) ?></strong></td>
                                <td>
                                  <!-- Trigger Buttons -->
                                    <button class="btn btn-sm btn-warning" data-toggle="modal" data-target="#editModal<?= $row['id'] ?>">Edit</button>
                                    <button class="btn btn-sm btn-danger" data-toggle="modal" data-target="#deleteModal<?= $row['id'] ?>">Delete</button>
                                </td>
                            </tr>

                            <div class='modal fade' id='editModal<?= $row['id'] ?>' tabindex='-1' role='dialog' aria-labelledby='editModalLabel<?= $row['id'] ?>' aria-hidden='true'>
                              <div class='modal-dialog' role='document'>
                                <div class='modal-content'>
                                  <form method='POST' action=''>
                                    <div class='modal-header'>
                                      <h5 class='modal-title' id='editModalLabel<?= $row['id'] ?>'>Edit Fee Structure</h5>
                                      <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
                                        <span aria-hidden='true'>&times;</span>
                                      </button>
                                    </div>
                            
                                    <div class='modal-body'>
                                      <input type='hidden' name='id' value='<?= $row['id'] ?>' />
                                      <div class='form-group'>
                                        <label>Class</label>
                                        <input name='class' class='form-control' value='<?= htmlspecialchars($row['class']) ?>' required />
                                      </div>
                                      <div class='form-group'>
                                        <label>Term</label>
                                        <select name='term' class='form-control' required>
                                          <option <?= $row['term'] == 'First Term' ? 'selected' : '' ?>>First Term</option>
                                          <option <?= $row['term'] == 'Second Term' ? 'selected' : '' ?>>Second Term</option>
                                          <option <?= $row['term'] == 'Third Term' ? 'selected' : '' ?>>Third Term</option>
                                        </select>
                                      </div>
                                      <div class='form-group'>
                                        <label>Session</label>
                                        <input name='session' class='form-control' value='<?= htmlspecialchars($row['session']) ?>' required />
                                      </div>
                                      <div class='form-group'>
                                        <label>Amount</label>
                                        <input type='number' step='0.01' name='amount' class='form-control' value='<?= $row['amount'] ?>' required />
                                      </div>
                                    </div>
                            
                                    <div class='modal-footer'>
                                      <button type='submit' name='edit_fee_structure' class='btn btn-success'>Save Changes</button>
                                      <button type='button' class='btn btn-secondary' data-dismiss='modal'>Cancel</button>
                                    </div>
                                  </form>
                                </div>
                              </div>
                            </div>
                            
                            
                            <div class='modal fade' id='deleteModal<?= $row['id'] ?>' tabindex='-1' role='dialog' aria-labelledby='deleteModalLabel<?= $row['id'] ?>' aria-hidden='true'>
                              <div class='modal-dialog' role='document'>
                                <div class='modal-content'>
                                  <form method='POST' action=''>
                                    <div class='modal-header bg-danger text-white'>
                                      <h5 class='modal-title' id='deleteModalLabel<?= $row['id'] ?>'>Confirm Delete</h5>
                                      <button type='button' class='close text-white' data-dismiss='modal' aria-label='Close'>
                                        <span aria-hidden='true'>&times;</span>
                                      </button>
                                    </div>
                            
                                    <div class='modal-body'>
                                      <input type='hidden' name='id' value='<?= $row['id'] ?>' />
                                      Are you sure you want to delete fee structure for <strong><?= htmlspecialchars($row['class']) ?></strong>?
                                    </div>
                            
                                    <div class='modal-footer'>
                                      <button type='submit' name='delete_fee_structure' class='btn btn-danger'>Yes, Delete</button>
                                      <button type='button' class='btn btn-secondary' data-dismiss='modal'>Cancel</button>
                                    </div>
                                  </form>
                                </div>
                              </div>
                            </div>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
