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



if (strlen($_SESSION['sid']==0)) {

    header('location:logout.php');

} 

require_once 'vendor/autoload.php';

include('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];


// Handle the form submission

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reference'])) {

    $reference = mysqli_real_escape_string($con, $_POST['reference']); // Sanitize input



    // Load environment variables

    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);

    $dotenv->load();



    $paystackSecretKey = $_ENV['PAYSTACK_SECRET_KEY'];



    // Ensure Paystack key is set

    if (empty($paystackSecretKey)) {

        die("Paystack Secret Key is not set. Please check your environment file.");

    }



    // Verify payment via Paystack API

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://api.paystack.co/transaction/verify/" . $reference);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_HTTPHEADER, [

        "Authorization: Bearer $paystackSecretKey",

        "Content-Type: application/json"

    ]);

    $response = curl_exec($ch);

    $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Capture HTTP status

    curl_close($ch);



    $responseData = json_decode($response, true);



    // Check if the transaction was successful

    if ($httpStatus === 200 && $responseData['status'] && $responseData['data']['status'] === 'success') {

        $amountPaid = $responseData['data']['amount'] / 100;

        $feeType = $responseData['data']['metadata']['custom_fields'][0]['value'] ?? 'Unknown';

        $email = $responseData['data']['customer']['email'];

        $studentno = $responseData['data']['metadata']['studentno'] ?? 'Manual Entry';

        $studentName = $responseData['data']['metadata']['studentName'] ?? 'Manual Entry';

        $stdid = $responseData['data']['metadata']['student_id'] ?? 0;



        // Save or update payment details into the database

        $paymentQuery = "INSERT INTO payments (student_id, studentno, studentName, email, reference, amount, status, fee_type, payment_date) 

                         VALUES ('$stdid', '$studentno', '$studentName', '$email', '$reference', $amountPaid, 'approved', '$feeType', NOW())

                         ON DUPLICATE KEY UPDATE status='approved', amount=$amountPaid, payment_date=NOW()";



        if (mysqli_query($con, $paymentQuery)) {

            $message = "Payment successfully reconciled. Reference: $reference.";

        } else {

            $errorMsg = mysqli_error($con);

            error_log("Database Error: $errorMsg", 3, 'error_log.txt'); // Log error

            $message = "Error saving payment. Please try again.";

        }

    } else {

        $errorMessage = $responseData['message'] ?? "Transaction failed.";

        error_log("API Error: $errorMessage", 3, 'error_log.txt'); // Log error

        $message = "Payment verification failed: $errorMessage.";

    }

}

?>



<!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"); ?>

    <!-- Main Sidebar Container -->

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



    <!-- Content Wrapper -->

    <div class="content-wrapper">

      <!-- Content 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">

                            Payment Management

                                <span class="premium-subtitle text-secondary">Payment Reconcilation</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"><a href="approve.php" class="text-primary">Approve Payment</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Reconcile Payment</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>



      <!-- Main content -->

      <section class="content">

        <div class="container-fluid">

          <div class="card card-primary">

            <div class="card-header">

              <h5 class="card-title font-weight-bold">

                      <i class="fas fa-exchange"></i> Reconcile Payment

              </h5>  

            </div>

            <div class="card-body">

              <?php if (isset($message)): ?>

                <div class="alert alert-<?php echo strpos($message, 'successfully') !== false ? 'success' : 'danger'; ?>">

                    <?php echo $message; ?>

                </div>

              <?php endif; ?>

              <form action="reconcile_payment.php" method="POST">

                <div class="form-group">

                  <label for="reference">Transaction Reference:</label>

                  <input type="text" name="reference" id="reference" class="form-control" required>

                </div>

                <center>

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

                </center>

              </form>

            </div>

          </div>

        </div>

      </section>

    </div>



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

  </div>



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

</body>

</html>

