<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting(0);

include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');

require_once __DIR__ . '/includes/fee_records_upsert.php';

if (!isset($_SESSION['sid']) || strlen((string) $_SESSION['sid']) == 0) {

  header('location:logout.php');

} else {

  if (isset($_POST['submit'])) {

    $name = trim($_POST['fee'] ?? '');

    $class = trim($_POST['class'] ?? '');

    $stream = trim($_POST['stream'] ?? '');

    $amount = (float) ($_POST['amount'] ?? 0);

    $std = trim($_POST['std'] ?? '');

    $redirect = trim($_POST['redirect_page'] ?? '');

    $feeSession = trim($_POST['fee_session'] ?? '');

    $feeTerm = trim($_POST['fee_term'] ?? '');

    if ($feeSession === '' || $feeTerm === '') {

      flash_alert('Please select academic session and term for this fee.');

    } elseif ($name === '' || $class === '' || $stream === '' || $std === '' || $redirect === '') {

      flash_alert('Please complete all fee fields.');

    } else {

      $con->begin_transaction();

      $catalogueUpdated = false;

      $chk = $con->prepare('SELECT id FROM fees WHERE name = ? AND class = ? AND stream = ? AND student_type = ? AND redirect_page = ? ORDER BY id DESC LIMIT 1');

      $existingId = 0;

      if ($chk) {

        $chk->bind_param('sssss', $name, $class, $stream, $std, $redirect);

        $chk->execute();

        $rowFound = $chk->get_result()->fetch_assoc();

        $chk->close();

        if ($rowFound) {

          $existingId = (int) $rowFound['id'];

        }

      }

      $stmtFees = null;

      if ($existingId > 0) {

        $stmtFees = $con->prepare('UPDATE fees SET amount = ? WHERE id = ?');

        $insertOk = $stmtFees && $stmtFees->bind_param('di', $amount, $existingId) && $stmtFees->execute();

        $catalogueUpdated = true;

      } else {

        $stmtFees = $con->prepare('INSERT INTO fees(name,class,stream,amount,student_type,redirect_page) VALUES (?,?,?,?,?,?)');

        $insertOk = $stmtFees && $stmtFees->bind_param('sss' . 'd' . 'ss', $name, $class, $stream, $amount, $std, $redirect) && $stmtFees->execute();

      }

      if ($insertOk) {

        $upsertOk = fee_records_upsert($con, $name, $class, $stream, $std, $feeSession, $feeTerm, $amount);

        if ($upsertOk) {

          $con->commit();

          if ($stmtFees) { $stmtFees->close(); }

          if ($catalogueUpdated) {

            flash_alert('Catalogue amount updated; session/term amount saved for ' . $feeSession . ' — ' . $feeTerm . '. (Same fee definition; no duplicate catalogue row.)');

          } else {

            flash_alert('New fee added; catalogue and session/term amount saved for ' . $feeSession . ' — ' . $feeTerm . '.');

          }

          header('Location: addfees.php'); exit;

        }

      }

      $con->rollback();

      if ($stmtFees) { $stmtFees->close(); }

      flash_alert($insertOk ? 'Could not save the session/term fee amount. No changes were applied.' : 'Something Went Wrong. Please try again.');

    }

  }
  

  // Handle adding session

  if (isset($_POST['add_fee'])) {

    $fee_namee = trim($_POST['fee_name']);

    if (!empty($fee_namee)) {

      // Check if fee name already exists

      $check_stmt = $con->prepare("SELECT id FROM fee_name WHERE name = ?");

      $check_stmt->bind_param("s", $fee_namee);

      $check_stmt->execute();

      $check_stmt->store_result();



      if ($check_stmt->num_rows == 0) {

        // Insert new fee name

        $stmt = $con->prepare("INSERT INTO fee_name (name) VALUES (?)");

        $stmt->bind_param("s", $fee_namee);

        if ($stmt->execute()) {

          flash_alert('Fee added successfully!');

        } else {

          flash_alert('Failed to add fee. Please try again.');

        }

      } else {

        flash_alert('Fee name already exists.');

      }

    } else {

      flash_alert('Please enter a fee name.');

    }

  }





  // Fetch classes

  $sql = "SELECT DISTINCT class FROM class_section ORDER BY class ASC";

  $result = $con->query($sql);

  $sessionsList = [];

  $sessRes = $con->query("SELECT id, session_name FROM school_sessions ORDER BY session_name DESC");

  if ($sessRes) {

    while ($r = $sessRes->fetch_assoc()) {

      $sessionsList[] = $r;

    }

  }

  $termsBySession = [];

  $termsRes = $con->query("SELECT session_id, term_name FROM school_terms ORDER BY start_date ASC");

  if ($termsRes) {

    while ($r = $termsRes->fetch_assoc()) {

      $sid = (int) $r['session_id'];

      if (!isset($termsBySession[$sid])) {

        $termsBySession[$sid] = [];

      }

      $termsBySession[$sid][] = $r['term_name'];

    }

  }

  $termsBySessionJson = json_encode($termsBySession);

  $currentTermNameJson = json_encode($currentTermName);

  $defaultSessionId = (int) $stResult['session_id'];

?>

  <!DOCTYPE html>

  <html>

  <?php @include("includes/head.php"); ?>



  <body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

      <!-- Navbar -->

      <?php @include("includes/header.php"); ?>

      <!-- /.navbar -->



      <!-- Main Sidebar Container -->

      <?php @include("includes/sidebar.php"); ?>



      <!-- Content Wrapper. Contains page content -->

      <div class="content-wrapper">

        <!-- Content Header (Page header) -->

<section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

            <div class="row align-items-center">

                <div class="col-md-8">

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

                            <i class="fas fa-wallet"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Fees Management

                                <span class="premium-subtitle text-secondary">Manage Fees</span>

                            </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <nav aria-label="breadcrumb">

                        <ol class="breadcrumb premium-breadcrumb">

                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Add Fees</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section> 





        <!-- Main content -->

        <section class="content">

          <div class="container-fluid">

            <div class="row ">

              <!-- Add Session -->

              <div class="col-md-12">

                <div class="card shadow">

                  <div class="card-header bg-primary text-white">

                    <h5 class="card-title mb-0 font-weight-bold"><i class="fas fa-file-invoice"></i> Add New Fee Name</h5>

                  </div>

                  <div class="card-body">

                    <form method="POST" enctype="multipart/form-data">

                      <div class="form-group col-md-12">

                        <label for="session">Fee Name (eg. Lesson Fees)</label>

                        <input type="text" class="form-control" name="fee_name" placeholder="Enter fee name" required>

                      </div>

                      <div class="text-center">

                        <button type="submit" name="add_fee" class="btn btn-primary"><i class="fas fa-check-circle"></i> Add fee Name</button>

                      </div>

                    </form>

                  </div>

                </div>



                <div class="col-md-12">

                  <div class="card card-primary">

                    <div class="card-header">

                      <h3 class="card-title font-weight-bold"><i class="fas fa-file-invoice"></i> Create New Fee</h3>

                    </div>

                    <form method="POST">

                      <div class="card-body">

                        <h5 style="color: brown">Fee Details</h5>

                        <p class="text-muted small mb-2">Choose the academic session and term this amount applies to. Payments use that session/term amount first, then fall back to the catalogue if needed.</p>

                        <p class="small mb-2"><strong>When to use this form vs Fees List:</strong> Use <em>Create New Fee</em> the first time you define a fee (fee name + class + school type + student type + approval page). For a <strong>new session or term</strong>, submit again with the same selections and the new session/term — the catalogue row is <strong>updated</strong> (not duplicated) and the amount for that period is saved. To change only an existing line, you can also use <a href="feelist.php">Fees List → Edit</a>.</p>

                        <hr>

                        <div class="row">

                          <div class="form-group col-md-4">

                            <label for="fee_session">Academic session</label>

                            <select class="form-control" name="fee_session" id="fee_session" required>

                              <option value="">-- Select session --</option>

                              <?php foreach ($sessionsList as $s): ?>

                                <option value="<?= htmlspecialchars($s['session_name']) ?>" data-session-id="<?= (int) $s['id'] ?>" <?= ((int) $s['id'] === $defaultSessionId) ? 'selected' : '' ?>><?= htmlspecialchars($s['session_name']) ?></option>

                              <?php endforeach; ?>

                            </select>

                          </div>

                          <div class="form-group col-md-4">

                            <label for="fee_term">Term</label>

                            <select class="form-control" name="fee_term" id="fee_term" required>

                              <option value="">-- Select term --</option>

                            </select>

                          </div>


                          <div class="form-group col-md-4">

                            <label for="session">Fee Name</label>

                            <select class="form-control" name="fee" id="fee" required>

                              <option value="">-- Select Fee Name--</option>

                              <option value="School Fees">School Fees (Student with Admission Number)</option>

                              <option value="School Fees (New Student)">School Fees (Student with Registration Number)</option>

                              <option value="School Fees (Scholarship Student)">School Fees (Student on Scholarship)</option>

                              <?php

                              $query = $con->query("SELECT id, name FROM fee_name ORDER BY id DESC");

                              while ($row = $query->fetch_assoc()) {



                                echo "<option value='{$row['name']}'>{$row['name']}</option>";

                              }

                              ?>

                            </select>

                          </div>

                          <div class="form-group col-md-4">

                            <label for="class">Class</label>

                            <select class="form-control" id="class" name="class" required>

                              <option value="">---Select Class---</option>

                              <option value="All student">All Class (For All Students)</option>

                              <option value="Incoming student">All Class (For Incoming Students)</option>

                              <option value="External student">All Class (For External Students)</option>

                              <option value="Graduated student">All Class (For Graduated Students)</option>

                              <?php while ($row = $result->fetch_assoc()): ?>

                                <option value="<?= htmlspecialchars($row["class"]) ?>"><?= htmlspecialchars($row["class"]) ?></option>

                              <?php endwhile; ?>

                            </select>

                          </div>

                          <div class="form-group col-md-4">

                            <label for="age">School Type</label>

                            <select type="select" class="form-control" id="stream" name="stream" required>

                              <option value="">---Select School Type---</option>

                              <option value="All student">All Students (Both Day and Boarding)</option>

                              <option value="Day">Day Students (Day students only)</option>

                              <option value="Boarding">Boarding Students (Boarding students only)</option>

                              <option value="Incoming student">Incoming students (For Incoming Students)</option>

                              <option value="External Student">External Students (External Students only)</option>

                              <option value="Graduated student">Graduated Students (For Graduted Students only)</option>

                            </select>

                          </div>





                          <div class="form-group col-md-4">

                            <label for="age">Student Type</label>

                            <select type="select" class="form-control" id="std" name="std" required>

                              <option value="">---Select Student Type---</option>

                              <option value="All student">All Students (Fee Applicable to all students)</option>

                              <option value="Incoming student">Incoming Students (Fee Applicable to incoming student)</option>

                              <option value="External Student">External Students (Fee Applicable to external students only)</option>

                              <option value="New">New Students (Fee Applicable to students with Reg. No)</option>

                              <option value="Old">Admitted Students (Fee Applicable to students with Admission No.)</option>

                              <option value="Scholarship Student">Scholarship Students (Fee Applicable to students on scholarship)</option>

                              <option value="Graduated student">Graduated Students (Fee Applicable to graduated students) </option>

                            </select>

                          </div>



                          <div class="form-group col-md-4">

                            <label for="amount">Amount</label>

                            <input type="number" class="form-control" name="amount" placeholder="Enter Amount" step="0.00001" required>

                          </div>



                          <div class="form-group col-md-4">

                            <label for="redirect_page">Approval Page</label>

                            <select class="form-control" name="redirect_page" id="redirect_page" required>

                              <option value="">----Select Approval Page----</option>

                              <option value="pay_tuition.php">Admitted Students School Fees Approval</option>

                              <option value="pay.php">Non Admitted Students School Fees Approval</option>

                              <option value="entrancepay.php">Entrance Form Approval</option>

                              <option value="acec.php">Admitted Students Lesson Fees Approval</option>

                              <option value="entrancepay1.php">External students Lesson Fees Approval</option>

                              <option value="entrancepay2.php">Certificate/Document Approval</option>

                              <option value="otherpay.php">Other Payments</option>

                            </select>

                          </div>

                        </div>

                      </div>



                      <div class="card-footer">

                        <center><button type="submit" name="submit" class="btn btn-primary"><i class="fas fa-check-circle"></i> Submit</button></center>

                      </div>

                    </form>

                  </div>

                </div>

                <!-- /.col -->

              </div>

              <!-- /.row -->

            </div>

            <!-- /.container-fluid -->

        </section>

        <!-- /.content -->

      </div>

      <!-- /.content-wrapper -->

      <?php @include("includes/footer.php"); ?>



    </div>



    <!-- ./wrapper -->

    <?php @include("includes/foot.php"); ?>



    <script src="dist/js/select2.min.js"></script>



    <script>

      // In your Javascript (external .js resource or <script> tag)

      var termsBySession = <?= $termsBySessionJson ?>;

      var currentTermForFees = <?= $currentTermNameJson ?>;

      function rebuildFeeTermOptions() {

        var $s = $('#fee_session option:selected');

        var sid = parseInt($s.data('session-id'), 10) || 0;

        var $t = $('#fee_term');

        $t.empty().append($('<option>', { value: '', text: '-- Select term --' }));

        if (sid && termsBySession[sid]) {

          termsBySession[sid].forEach(function (name) {

            var opt = $('<option>').val(name).text(name);

            if (currentTermForFees && name === currentTermForFees) {

              opt.prop('selected', true);

            }

            $t.append(opt);

          });

        }

      }

      $(document).ready(function() {

        rebuildFeeTermOptions();

        $('#fee_session').on('change', rebuildFeeTermOptions);

        $('#fee_session').select2();

        $('#fee_term').select2();

      });

      $(document).ready(function() {

        $('#class').select2();



      });

      $(document).ready(function() {

        $('#redirect_page').select2();



      });

      $(document).ready(function() {



        $('#stream').select2();





      });

      $(document).ready(function() {



        $('#ocupation').select2();



      });



      $(document).ready(function() {



        $('#country').select2();



      });



      $(document).ready(function() {



        $('#sex').select2();



      });

      $(document).ready(function() {



        $('#std').select2();



      });

      $(document).ready(function() {



        $('#fee').select2();



      });

    </script>

  </body>



  </html>

<?php

} ?>