<?php
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once("public/connection.php");

/* =========================
VARIABLES
========================= */

$reg = $_POST['reg_number'] ?? ($_GET['reg'] ?? '');
$family_regno = $_POST['family_regno'] ?? ($_GET['family_regno'] ?? '');
$amount = $_POST['fee_payment_amount'] ?? '';
$selected_term = $_POST['fee_term'] ?? '';
$selected_session = $_POST['fee_session'] ?? '';

$students = [];
$fee_rows = [];
$total_outstanding = 0;
$payment_type = null;


/* =========================
TERMS & SESSIONS
========================= */

$terms = ['First Term','Second Term','Third Term'];

$sessions = [];
$res = $connection->query("SELECT sessions FROM sessions ORDER BY id DESC");

while($row = $res->fetch_assoc()){
$sessions[] = $row['sessions'];
}

if(!$selected_term || !$selected_session){

$cs = $connection->query("SELECT current_term,current_session FROM current_season LIMIT 1")->fetch_assoc();

$selected_term = $cs['current_term'];
$selected_session = $cs['current_session'];

}


/* =========================
FETCH STUDENTS
========================= */

if($reg){

$stmt = $connection->prepare("
SELECT id,reg_number,family_regno,class,
CONCAT(firstname,' ',COALESCE(othername,''),' ',lastname) AS student_name
FROM students
WHERE reg_number=?
LIMIT 1
");

$stmt->bind_param("s",$reg);
$stmt->execute();

$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if($student){

$students[] = $student;
$family_regno = $student['family_regno'];
$payment_type='individual';

}

}


elseif($family_regno){

$stmt = $connection->prepare("
SELECT id,reg_number,family_regno,class,
CONCAT(firstname,' ',COALESCE(othername,''),' ',lastname) AS student_name
FROM students
WHERE family_regno=?
");

$stmt->bind_param("s",$family_regno);
$stmt->execute();

$res = $stmt->get_result();

while($row = $res->fetch_assoc()){
$students[]=$row;
}

$stmt->close();

if(count($students)) $payment_type='family';

}



/* =========================
CALCULATE OUTSTANDING
========================= */

if($payment_type && count($students)){

if($payment_type=='individual'){

$s = $students[0];

$stmt = $connection->prepare("
SELECT id,total_fee,amount_paid,custom_ref
FROM fee_payment
WHERE reg_number=? AND fee_term=? AND fee_session=?
LIMIT 1
");

$stmt->bind_param("sss",$s['reg_number'],$selected_term,$selected_session);
$stmt->execute();

$fee = $stmt->get_result()->fetch_assoc();
$stmt->close();

if($fee){

$balance = max($fee['total_fee'] - $fee['amount_paid'],0);

$total_outstanding = $balance;

$fee_rows[]=[
'id'=>$fee['id'],
'reg'=>$s['reg_number'],
'name'=>$s['student_name'],
'class'=>$s['class'],
'balance'=>$balance
];

}

}



elseif($payment_type=='family'){

$student_ids = [];

foreach($students as $st){

$stmt = $connection->prepare("
SELECT id,total_fee,amount_paid
FROM fee_payment
WHERE reg_number=? AND fee_term=? AND fee_session=?
LIMIT 1
");

$stmt->bind_param("sss",$st['reg_number'],$selected_term,$selected_session);
$stmt->execute();

$fee = $stmt->get_result()->fetch_assoc();
$stmt->close();

if($fee){

$balance = max($fee['total_fee'] - $fee['amount_paid'],0);

$total_outstanding += $balance;

$student_ids[]=$fee['id'];

}

}

$fee_rows[]=[
'ids'=>$student_ids,
'students'=>$students,
'family_regno'=>$family_regno,
'total_outstanding'=>$total_outstanding
];

}

}



/* =========================
SAVE PAYMENT
========================= */

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

if(!$amount){

$_SESSION['msg']="Enter payment amount";
$_SESSION['type']="danger";

header("Location: fee_payment");
exit;

}


/* INDIVIDUAL PAYMENT */

if($payment_type=='individual'){

$row=$fee_rows[0];

$stmt=$connection->prepare("SELECT total_fee,amount_paid FROM fee_payment WHERE id=?");
$stmt->bind_param("i",$row['id']);
$stmt->execute();

$fee=$stmt->get_result()->fetch_assoc();
$stmt->close();

$new_paid=min($fee['amount_paid']+$amount,$fee['total_fee']);

$balance=$fee['total_fee']-$new_paid;

$status=$balance<=0?'paid':'pending';

$custom_ref="STD".time().rand(100,999);


/* RECEIPT */

$receipt_name=null;

if(!empty($_FILES['receipt']['name'])){

$dir="uploads/receipts/";

if(!is_dir($dir)) mkdir($dir,0777,true);

$tmp=$_FILES['receipt']['tmp_name'];
$ext=strtolower(pathinfo($_FILES['receipt']['name'],PATHINFO_EXTENSION));

if(in_array($ext,['jpg','jpeg','png','pdf'])){

$receipt_name="receipt_".time().rand(1000,9999).".".$ext;

move_uploaded_file($tmp,$dir.$receipt_name);

}

}


$stmt=$connection->prepare("
UPDATE fee_payment
SET amount_paid=?,student_balance=?,payment_status=?,payment_date=NOW(),custom_ref=?
WHERE id=?
");

$stmt->bind_param("ddssi",$new_paid,$balance,$status,$custom_ref,$row['id']);
$stmt->execute();
$stmt->close();


$stmt=$connection->prepare("
INSERT INTO fee_payment_receipts
(fee_payment_id,reg_number,family_regno,amount_paid,receipt_file,uploaded_at)
VALUES (?,?,?,?,?,NOW())
");

$stmt->bind_param("issds",$row['id'],$row['reg'],$family_regno,$amount,$receipt_name);
$stmt->execute();
$stmt->close();


$_SESSION['msg']="Payment recorded. Balance ₦".number_format($balance,2);
$_SESSION['type']="success";

}



/* FAMILY PAYMENT */

elseif($payment_type=='family'){

$row=$fee_rows[0];

$remaining=$amount;

foreach($row['ids'] as $id){

$stmt=$connection->prepare("SELECT total_fee,amount_paid FROM fee_payment WHERE id=?");
$stmt->bind_param("i",$id);
$stmt->execute();

$fee=$stmt->get_result()->fetch_assoc();
$stmt->close();

$balance=$fee['total_fee']-$fee['amount_paid'];

if($remaining<=0) break;

$pay=min($remaining,$balance);

$new_paid=$fee['amount_paid']+$pay;

$new_balance=$fee['total_fee']-$new_paid;

$status=$new_balance<=0?'paid':'pending';

$custom_ref="FAM".time().rand(100,999);

$stmt=$connection->prepare("
UPDATE fee_payment
SET amount_paid=?,student_balance=?,payment_status=?,payment_date=NOW(),custom_ref=?
WHERE id=?
");

$stmt->bind_param("ddssi",$new_paid,$new_balance,$status,$custom_ref,$id);
$stmt->execute();
$stmt->close();

$remaining-=$pay;

}


/* RECEIPT */

$receipt_name=null;

if(!empty($_FILES['receipt']['name'])){

$dir="uploads/receipts/";

if(!is_dir($dir)) mkdir($dir,0777,true);

$tmp=$_FILES['receipt']['tmp_name'];
$ext=strtolower(pathinfo($_FILES['receipt']['name'],PATHINFO_EXTENSION));

if(in_array($ext,['jpg','jpeg','png','pdf'])){

$receipt_name="receipt_".time().rand(1000,9999).".".$ext;

move_uploaded_file($tmp,$dir.$receipt_name);

}

}

$student_regs=array_column($row['students'],'reg_number');

$stmt=$connection->prepare("
INSERT INTO fee_payment_receipts
(fee_payment_id,reg_number,family_regno,amount_paid,receipt_file,uploaded_at)
VALUES (?,?,?,?,?,NOW())
");

$first_id=$row['ids'][0];

$stmt->bind_param("issds",$first_id,implode(',',$student_regs),$row['family_regno'],$amount,$receipt_name);
$stmt->execute();
$stmt->close();

$_SESSION['msg']="Family payment recorded";
$_SESSION['type']="success";

}

header("Location: fee_payment");
exit;

}

?>

<div class="card p-4">

<h4 class="text-center mb-4">Record Fee Payment</h4>

<?php if(isset($_SESSION['msg'])): ?>

<div class="alert alert-<?= $_SESSION['type'] ?>">
<?= $_SESSION['msg'] ?>
</div>

<?php unset($_SESSION['msg'],$_SESSION['type']); endif; ?>


<!-- PAYMENT TYPE BUTTONS -->

<div class="text-center mb-4">

<button type="button" class="btn btn-primary btn-lg mx-2"
onclick="selectPaymentType('individual')">
👤 Individual Payment
</button>

<button type="button" class="btn btn-dark btn-lg mx-2"
onclick="selectPaymentType('family')">
👨‍👩‍👧‍👦 Family Payment
</button>

</div>


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


<div id="individualBox" style="display:none">

<div class="row mb-3">

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

<input type="text" name="reg_number"
class="form-control"
placeholder="Enter Student Registration Number"
value="<?= htmlspecialchars($reg ?? '') ?>">

</div>

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

<button class="btn btn-info w-100">Fetch</button>

</div>

</div>

</div>


<div id="familyBox" style="display:none">

<div class="row mb-3">

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

<input type="text" name="family_regno"
class="form-control"
placeholder="Enter Family Registration Number"
value="<?= htmlspecialchars($family_regno ?? '') ?>">

</div>

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

<button class="btn btn-info w-100">Fetch</button>

</div>

</div>

</div>



<div class="row mb-3">

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

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

<?php foreach($terms as $t): ?>

<option value="<?= $t ?>" <?= $t==$selected_term?'selected':'' ?>>
<?= $t ?>
</option>

<?php endforeach; ?>

</select>

</div>


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

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

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

<option value="<?= $s ?>" <?= $s==$selected_session?'selected':'' ?>>
<?= $s ?>
</option>

<?php endforeach; ?>

</select>

</div>

</div>


<?php if(count($fee_rows)): ?>

<hr>

<h5>Outstanding Fees</h5>

<table class="table table-bordered">

<tr>
<th>Student(s)</th>
<th>Reg / Family</th>
<th>Class</th>
<th>Balance</th>
</tr>

<?php foreach($fee_rows as $row): ?>

<tr>

<td>

<?php
if($payment_type=='individual'){
echo $row['name'];
}else{
echo implode(', ',array_column($row['students'],'student_name'));
}
?>

</td>

<td><?= $payment_type=='individual'?$row['reg']:$row['family_regno'] ?></td>

<td>

<?php
if($payment_type=='individual'){
echo $row['class'];
}else{
echo implode('<br>',array_column($row['students'],'class'));
}
?>

</td>

<td>₦<?= number_format($row['balance'] ?? $row['total_outstanding'],2) ?></td>

</tr>

<?php endforeach; ?>

</table>


<div class="row mt-3">

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

<input type="number" step="0.01"
name="fee_payment_amount"
class="form-control"
value="<?= $total_outstanding ?>"
required>

</div>

</div>


<div class="row mt-3">

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

<label>Upload Receipt</label>

<input type="file" name="receipt"
class="form-control"
accept="image/*,.pdf">

</div>

</div>

<button name="save_fee"
class="btn btn-success btn-lg w-100 mt-3">
Save Payment
</button>

<?php endif; ?>

</form>



<?php if($reg || $family_regno): ?>

<h5>Transaction History</h5>

<table class="table table-bordered">
<tr>
<th>Student(s)</th>
<th>Reg / Family</th>
<th>Reference</th>
<th>Amount</th>
<th>Receipt</th>
<th>Date</th>
</tr>

<?php
$stmt = $connection->prepare("
    SELECT r.*, f.custom_ref
    FROM fee_payment_receipts r
    LEFT JOIN fee_payment f ON r.fee_payment_id = f.id
    WHERE r.reg_number=? OR r.family_regno=?
    ORDER BY r.uploaded_at DESC
");
$stmt->bind_param("ss", $reg, $family_regno);
$stmt->execute();
$history = $stmt->get_result();

while ($p = $history->fetch_assoc()):

    // Fetch student names
    if ($p['family_regno']) {
        $stmt2 = $connection->prepare("
            SELECT CONCAT(firstname,' ',COALESCE(othername,''),' ',lastname) AS name
            FROM students
            WHERE family_regno=?
        ");
        $stmt2->bind_param("s", $p['family_regno']);
        $stmt2->execute();
        $res = $stmt2->get_result();
        $names = [];
        while ($n = $res->fetch_assoc()) $names[] = $n['name'];
        $stmt2->close();
        $student_display = implode(', ', $names);
    } else {
        $stmt2 = $connection->prepare("
            SELECT CONCAT(firstname,' ',COALESCE(othername,''),' ',lastname) AS name
            FROM students
            WHERE reg_number=?
            LIMIT 1
        ");
        $stmt2->bind_param("s", $p['reg_number']);
        $stmt2->execute();
        $res = $stmt2->get_result()->fetch_assoc();
        $stmt2->close();
        $student_display = $res['name'] ?? $p['reg_number'];
    }
?>
<tr>
<td><?= htmlspecialchars($student_display) ?></td>
<td><?= htmlspecialchars($p['family_regno'] ?: $p['reg_number']) ?></td>
<td><?= htmlspecialchars($p['custom_ref'] ?? '-') ?></td>
<td>₦<?= number_format($p['amount_paid'], 2) ?></td>
<td>
<?php
$folder = "/uploads/receipts/";

if (!empty($p['receipt_file']) && file_exists($_SERVER['DOCUMENT_ROOT'].$folder.$p['receipt_file'])) {

    echo '<a href="'.$folder.$p['receipt_file'].'" target="_blank" class="btn btn-sm btn-success">View</a> ';
    echo '<a href="'.$folder.$p['receipt_file'].'" download class="btn btn-sm btn-primary">Download</a> ';
    echo '<a href="/portal/print_fees.php?receipt_id='.$p['id'].'" target="_blank" class="btn btn-sm btn-danger" style="color:white;">
            <i class="fa fa-print"></i> Print PDF</a>';

} else {

    echo '<span class="text-muted">No Receipt</span>';

}
?>
</td>
<td><?= date("d-M-Y H:i", strtotime($p['uploaded_at'])) ?></td>
</tr>
<?php endwhile; ?>
</table>


<?php endif; ?>

</div>


<script>

function selectPaymentType(type){

document.getElementById("individualBox").style.display="none";
document.getElementById("familyBox").style.display="none";

if(type==="individual"){
document.getElementById("individualBox").style.display="block";
}

if(type==="family"){
document.getElementById("familyBox").style.display="block";
}

}

</script>