<?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 __DIR__ . '/includes/dbconnection.php';

include __DIR__ . '/includes/flash.php';

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

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

$stResult = resolveCurrentSessionTerm($con);

$currentSessionName = $stResult['session_name'];

$currentTermName = $stResult['term_name'];

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

$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);

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

    header('HTTP/1.1 403 Forbidden');

    exit('Unauthorized');

}

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

    $feeId = (int) ($_POST['fee_id'] ?? 0);

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

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

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

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

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

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

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

    if ($feeId < 1 || $feeSession === '' || $feeTerm === '' || $name === '' || $class === '' || $stream === '' || $student_type === '') {

        echo "<script>alert('Please complete all fields, including session and term.');</script>";

        exit;

    }

    $con->begin_transaction();

    $upd = $con->prepare("UPDATE fees SET name = ?, class = ?, stream = ?, amount = ?, student_type = ? WHERE id = ?");

    $ok = $upd && $upd->bind_param('sssdsi', $name, $class, $stream, $amount, $student_type, $feeId) && $upd->execute();

    if ($ok) {

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

        if ($upsertOk) {

            $con->commit();

            if ($upd) {

                $upd->close();

            }

            echo "<script>alert('Updated successfully.'); window.location.href='feelist.php';</script>";

            exit;

        }

    }

    $con->rollback();

    if ($upd) {

        $upd->close();

    }

    echo "<script>alert('Something went wrong. No changes were applied.');</script>";

    exit;

}

$eid = isset($_POST['edit_id']) ? (int) $_POST['edit_id'] : 0;

if ($eid < 1) {

    exit;

}

$ret = $con->prepare('SELECT * FROM fees WHERE id = ? LIMIT 1');

$ret->bind_param('i', $eid);

$ret->execute();

$res = $ret->get_result();

$row = $res->fetch_assoc();

$ret->close();

if (!$row) {

    exit;

}

$prefSessionName = $currentSessionName;

$prefTermName = $currentTermName;

$frStmt = $con->prepare('SELECT session, term FROM fee_records WHERE name = ? AND class = ? AND stream = ? AND student_type = ? ORDER BY id DESC LIMIT 1');

if ($frStmt) {

    $frStmt->bind_param('ssss', $row['name'], $row['class'], $row['stream'], $row['student_type']);

    $frStmt->execute();

    $frRow = $frStmt->get_result()->fetch_assoc();

    $frStmt->close();

    if ($frRow && !empty($frRow['session']) && !empty($frRow['term'])) {

        $prefSessionName = $frRow['session'];

        $prefTermName = $frRow['term'];

    }

}

$prefSessionId = $defaultSessionId;

foreach ($sessionsList as $s) {

    if ((string) $s['session_name'] === (string) $prefSessionName) {

        $prefSessionId = (int) $s['id'];

        break;

    }

}

?>

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

<div class="card-body">

  <input type="hidden" id="efc_terms_json" value="<?php echo htmlspecialchars($termsBySessionJson, ENT_QUOTES, 'UTF-8'); ?>">

  <input type="hidden" id="efc_pref_term" value="<?php echo htmlspecialchars((string) $prefTermName, ENT_QUOTES, 'UTF-8'); ?>">

  <!-- Main content -->

  <section class="content">

    <div class="container-fluid">

      <div class="row">

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

          <div class="card">

            <div class="card-header p-2">

              <ul class="nav nav-pills">

                <li class="nav-item"><a class="nav-link active" href="#companydetail" data-toggle="tab">Fees Details</a></li>

              </ul>

            </div><!-- /.card-header -->

            <div class="card-body">

              <div class="tab-content">

                <div class="active tab-pane" id="companydetail">

                  <p class="text-muted small">Update the catalogue amount and the amount for the selected session and term.</p>


                  <form role="form" method="post" action="editfees.php" enctype="multipart/form-data" class="form-horizontal">

                    <input type="hidden" name="fee_id" value="<?php echo (int) $row['id']; ?>">

                    <div class="row">

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

                        <div class="form-group">

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

                          <input name="name" class="form-control" id="name" value="<?php echo htmlspecialchars($row['name']); ?>" required readonly>

                        </div>

                      </div>

                    </div><!-- ./row -->

                    <div class="row">

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

                        <div class="form-group">

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

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

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

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

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

                            <?php endforeach; ?>

                          </select>

                        </div>

                      </div>

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

                        <div class="form-group">

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

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

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

                          </select>

                        </div>

                      </div>


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

                        <div class="form-group">

                          <label>Class</label>

                          <input class="form-control" name="class" value="<?php echo htmlspecialchars($row['class']); ?>" required readonly>

                        </div>

                      </div>

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

                        <div class="form-group">

                          <label>School Type</label>

                          <input class="form-control" name="stream" value="<?php echo htmlspecialchars($row['stream']); ?>" required readonly>

                        </div>

                      </div>

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

                        <div class="form-group">

                          <label>Student Type</label>

                          <input class="form-control" name="std" value="<?php echo htmlspecialchars($row['student_type']); ?>" required readonly>

                        </div>

                      </div>

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

                        <div class="form-group">

                          <label>Amount</label>

                          <input type="number" step="0.00001" class="form-control" name="amount" value="<?php echo htmlspecialchars($row['amount']); ?>" required>

                        </div>

                      </div>

                    </div>

                    <div class="modal-footer text-right">

                      <button type="submit" name="submit" class="btn btn-primary">Update</button>

                    </div>

                  </form>

                </div>

              </div>

            </div><!-- /.card-body -->

          </div>

        </div>

      </div>

    </div>

  </section>

</div>
