<?php
require __DIR__.'/includes/layout.php';
require_module_access('loan_advance','payroll.reports');
if(role_code()!=='SUPER_ADMIN'){http_response_code(403);exit('Access denied. Loan & Advance is restricted to Super Admin.');}

$tab=$_GET['tab']??'register';
if($tab==='types'){header('Location: payroll_master.php?tab=loan_types');exit;}
if($tab==='purposes'){header('Location: payroll_master.php?tab=loan_purposes');exit;}
$scheduleMonth=$_GET['schedule_month']??date('Y-m');if(!preg_match('/^\d{4}-\d{2}$/',$scheduleMonth))$scheduleMonth=date('Y-m');
$search=trim($_GET['search']??'');
$status=trim($_GET['status']??'');
$type=trim($_GET['type']??'');
$purpose=trim($_GET['purpose']??'');
$dept=trim($_GET['department']??'');
$masterStatus=trim($_GET['master_status']??'');
$viewId=(int)($_GET['view']??0);
$editId=(int)($_GET['edit']??0);
$viewTypeId=(int)($_GET['view_type']??0);
$editTypeId=(int)($_GET['edit_type']??0);
$viewPurposeId=(int)($_GET['view_purpose']??0);
$editPurposeId=(int)($_GET['edit_purpose']??0);

function la_redirect(array $q=[]):void{
    header('Location: loan_advance.php'.($q?'?'.http_build_query($q):''));exit;
}
function la_expected_month(string $start,float $amount,float $monthly):?string{
    if(!preg_match('/^\d{4}-\d{2}$/',$start)||$amount<=0||$monthly<=0)return null;
    $n=max(1,(int)ceil($amount/$monthly));
    $d=new DateTimeImmutable($start.'-01');
    return $d->modify('+'.($n-1).' months')->format('Y-m');
}
function la_balance(int $id,float $original):float{
    $s=db()->prepare("SELECT COALESCE(SUM(amount),0) FROM loan_repayments WHERE loan_id=?");$s->execute([$id]);
    return max(0,$original-(float)$s->fetchColumn());
}
function la_upload_dir():string{
    $d=__DIR__.'/storage/loan_attachments';
    if(!is_dir($d)&&!mkdir($d,0750,true))throw new RuntimeException('Unable to create loan attachment storage.');
    $ht=$d.'/.htaccess';
    if(!is_file($ht))@file_put_contents($ht,"Require all denied\nDeny from all\n");
    return $d;
}
function la_handle_attachments(int $loanId):void{
    if(empty($_FILES['attachments'])||!isset($_FILES['attachments']['name'])||!is_array($_FILES['attachments']['name']))return;
    $allowedExt=['pdf','jpg','jpeg','png','doc','docx','xls','xlsx'];
    $allowedMime=[
      'application/pdf','image/jpeg','image/png',
      'application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/zip','application/octet-stream'
    ];
    $dir=la_upload_dir();$finfo=new finfo(FILEINFO_MIME_TYPE);
    foreach($_FILES['attachments']['name'] as $i=>$orig){
        $err=(int)($_FILES['attachments']['error'][$i]??UPLOAD_ERR_NO_FILE);
        if($err===UPLOAD_ERR_NO_FILE||trim((string)$orig)==='')continue;
        if($err!==UPLOAD_ERR_OK)throw new RuntimeException('Attachment upload failed: '.basename((string)$orig));
        $size=(int)($_FILES['attachments']['size'][$i]??0);
        if($size<=0||$size>10*1024*1024)throw new RuntimeException('Each attachment must be 10 MB or smaller.');
        $tmp=$_FILES['attachments']['tmp_name'][$i]??'';
        $ext=strtolower(pathinfo((string)$orig,PATHINFO_EXTENSION));
        $mime=$finfo->file($tmp)?:'application/octet-stream';
        if(!in_array($ext,$allowedExt,true)||!in_array($mime,$allowedMime,true))
            throw new RuntimeException('Unsupported attachment type: '.basename((string)$orig));
        $stored=bin2hex(random_bytes(18)).'.'.$ext;
        if(!move_uploaded_file($tmp,$dir.'/'.$stored))throw new RuntimeException('Unable to save attachment.');
        db()->prepare("INSERT INTO loan_documents(loan_id,original_name,stored_name,mime_type,file_size,uploaded_by,uploaded_at)
            VALUES(?,?,?,?,?,?,NOW())")->execute([$loanId,basename((string)$orig),$stored,$mime,$size,user()['id']]);
        audit('UPLOAD','loan_document',(string)$loanId,'Loan attachment uploaded: '.basename((string)$orig));
    }
}

if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();$a=$_POST['action']??'';

    if($a==='save_loan'){
        $id=(int)($_POST['id']??0);
        $eid=trim($_POST['employee_id']??'');
        $typeId=(int)($_POST['loan_type_id']??0);
        $purposeId=(int)($_POST['purpose_id']??0);
        $purposeText=trim($_POST['purpose_text']??'');
        $loanDate=$_POST['loan_date']??date('Y-m-d');
        $original=max(0,(float)($_POST['original_amount']??0));
        $monthly=max(0,(float)($_POST['monthly_deduction']??0));
        $method=$_POST['deduction_method']??'AUTO';if(!in_array($method,['AUTO','MANUAL'],true))$method='AUTO';
        $start=trim($_POST['deduction_start_month']??'');
        $expected=trim($_POST['expected_completion_month']??'')?:la_expected_month($start,$original,$monthly);

        $ts=db()->prepare("SELECT name FROM loan_type_master WHERE id=? AND is_active=1");$ts->execute([$typeId]);$loanType=(string)$ts->fetchColumn();
        if($eid===''||$loanType===''||$original<=0||$monthly<=0||!preg_match('/^\d{4}-\d{2}$/',$start))
            throw new RuntimeException('Employee, Loan Type, Original Amount, Monthly Deduction and Deduction Start Month are required.');
        if($purposeId){
            $ps=db()->prepare("SELECT name FROM loan_purpose_master WHERE id=? AND is_active=1");$ps->execute([$purposeId]);
            if(!$ps->fetchColumn())throw new RuntimeException('Selected purpose is not active.');
        }
        if($purposeId===0 && $purposeText==='')throw new RuntimeException('Please select a Purpose or enter Other Purpose.');

        if($id){
            db()->prepare("UPDATE staff_loans SET employee_id=?,loan_type_id=?,loan_type=?,purpose_id=?,purpose_text=?,loan_date=?,
                original_amount=?,monthly_deduction=?,deduction_method=?,deduction_start_month=?,expected_completion_month=?,reference_no=?,remarks=?,
                updated_by=?,updated_at=NOW() WHERE id=?")
                ->execute([$eid,$typeId,$loanType,$purposeId?:null,$purposeText,$loanDate,$original,$monthly,$method,$start,$expected,
                    trim($_POST['reference_no']??''),trim($_POST['remarks']??''),user()['id'],$id]);
            audit('UPDATE','staff_loan',(string)$id,'Loan / advance updated');
        }else{
            db()->prepare("INSERT INTO staff_loans(employee_id,loan_type_id,loan_type,purpose_id,purpose_text,loan_date,original_amount,
                monthly_deduction,deduction_method,deduction_start_month,expected_completion_month,status,reference_no,remarks,is_archived,created_by,created_at)
                VALUES(?,?,?,?,?,?,?,?,?, ?,?,'Active',?,?,0,?,NOW())")
                ->execute([$eid,$typeId,$loanType,$purposeId?:null,$purposeText,$loanDate,$original,$monthly,$method,$start,$expected,
                    trim($_POST['reference_no']??''),trim($_POST['remarks']??''),user()['id']]);
            $id=(int)db()->lastInsertId();audit('SAVE','staff_loan',(string)$id,'Loan / advance created');
        }
        la_handle_attachments($id);
        $_SESSION['flash']='Loan / advance saved.';
        la_redirect(['tab'=>'register','view'=>$id]);
    }

    if($a==='status'){
        $id=(int)$_POST['id'];$st=$_POST['loan_status']??'Active';
        if(!in_array($st,['Active','Suspended','Settled','Cancelled'],true))exit('Invalid status.');
        db()->prepare("UPDATE staff_loans SET status=?,updated_by=?,updated_at=NOW() WHERE id=?")->execute([$st,user()['id'],$id]);
        audit('STATUS','staff_loan',(string)$id,'Loan status changed to '.$st);
        la_redirect(['tab'=>'register','view'=>$id]);
    }

    if($a==='archive'){
        $id=(int)$_POST['id'];
        $s=db()->prepare("SELECT COUNT(*) FROM loan_repayments WHERE loan_id=?");$s->execute([$id]);$has=(int)$s->fetchColumn();
        $d=db()->prepare("SELECT COUNT(*) FROM loan_documents WHERE loan_id=?");$d->execute([$id]);$docs=(int)$d->fetchColumn();
        if($has||$docs){
            db()->prepare("UPDATE staff_loans SET is_archived=1,status='Cancelled',updated_by=?,updated_at=NOW() WHERE id=?")->execute([user()['id'],$id]);
            audit('ARCHIVE','staff_loan',(string)$id,'Loan archived because transaction/document history exists');
            $_SESSION['flash']='Loan has history/documents, so it was archived instead of permanently deleted.';
        }else{
            db()->prepare("DELETE FROM staff_loans WHERE id=?")->execute([$id]);
            audit('DELETE','staff_loan',(string)$id,'Unused loan deleted');
            $_SESSION['flash']='Unused loan deleted.';
        }
        la_redirect(['tab'=>'register']);
    }

    if($a==='manual_repayment'){
        $id=(int)$_POST['loan_id'];$amount=max(0,(float)($_POST['amount']??0));
        $s=db()->prepare("SELECT original_amount FROM staff_loans WHERE id=? AND is_archived=0");$s->execute([$id]);$orig=$s->fetchColumn();
        if($orig===false)throw new RuntimeException('Loan not found.');
        $bal=la_balance($id,(float)$orig);
        if($amount<=0||$amount>$bal+0.001)throw new RuntimeException('Repayment must be more than zero and cannot exceed the outstanding balance.');
        db()->prepare("INSERT INTO loan_repayments(loan_id,pay_month,payroll_result_id,amount,payment_date,source,reference_no,remarks,posted_by,created_at)
            VALUES(?,NULL,NULL,?,?,'Manual',?,?,?,NOW())")
            ->execute([$id,$amount,$_POST['payment_date']??date('Y-m-d'),trim($_POST['reference_no']??''),trim($_POST['remarks']??''),user()['id']]);
        $balAfter=la_balance($id,(float)$orig);
        if($balAfter<=0.001)db()->prepare("UPDATE staff_loans SET status='Settled',updated_at=NOW() WHERE id=?")->execute([$id]);
        audit('REPAYMENT','staff_loan',(string)$id,'Manual repayment '.number_format($amount,2));
        $_SESSION['flash']='Repayment posted.';
        la_redirect(['tab'=>'register','view'=>$id]);
    }

    if($a==='delete_manual_repayment'){
        $rid=(int)$_POST['repayment_id'];$loanId=(int)$_POST['loan_id'];
        $s=db()->prepare("SELECT source FROM loan_repayments WHERE id=? AND loan_id=?");$s->execute([$rid,$loanId]);
        if($s->fetchColumn()!=='Manual')exit('Only manual repayments may be deleted here.');
        db()->prepare("DELETE FROM loan_repayments WHERE id=? AND loan_id=?")->execute([$rid,$loanId]);
        $s=db()->prepare("SELECT original_amount,status FROM staff_loans WHERE id=?");$s->execute([$loanId]);$l=$s->fetch();
        if($l && $l['status']==='Settled' && la_balance($loanId,(float)$l['original_amount'])>0)
            db()->prepare("UPDATE staff_loans SET status='Active',updated_at=NOW() WHERE id=?")->execute([$loanId]);
        audit('DELETE','loan_repayment',(string)$rid,'Manual loan repayment deleted');
        la_redirect(['tab'=>'register','view'=>$loanId]);
    }

    if($a==='delete_document'){
        $docId=(int)$_POST['document_id'];$loanId=(int)$_POST['loan_id'];
        $s=db()->prepare("SELECT stored_name,original_name FROM loan_documents WHERE id=? AND loan_id=?");$s->execute([$docId,$loanId]);$doc=$s->fetch();
        if($doc){
            @unlink(la_upload_dir().'/'.$doc['stored_name']);
            db()->prepare("DELETE FROM loan_documents WHERE id=? AND loan_id=?")->execute([$docId,$loanId]);
            audit('DELETE','loan_document',(string)$docId,'Loan attachment deleted: '.$doc['original_name']);
        }
        la_redirect(['tab'=>'register','view'=>$loanId]);
    }

    if($a==='save_monthly_deduction'){
        $loanId=(int)($_POST['loan_id']??0);$pm=trim($_POST['pay_month']??'');$kind=$_POST['adjustment_type']??'OVERRIDE';$amount=max(0,(float)($_POST['amount']??0));$reason=trim($_POST['reason']??'');
        if(!preg_match('/^\d{4}-\d{2}$/',$pm))throw new RuntimeException('Valid Pay Month is required.');
        $s=db()->prepare("SELECT l.*,COALESCE((SELECT SUM(r.amount) FROM loan_repayments r WHERE r.loan_id=l.id),0) paid_amount FROM staff_loans l WHERE l.id=? AND l.is_archived=0");$s->execute([$loanId]);$l=$s->fetch();if(!$l)throw new RuntimeException('Loan not found.');
        $posted=db()->prepare("SELECT status FROM loan_monthly_deductions WHERE loan_id=? AND pay_month=?");$posted->execute([$loanId,$pm]);if($posted->fetchColumn()==='Posted')throw new RuntimeException('This pay month is already posted. Reopen payroll before changing it.');
        $balance=max(0,(float)$l['original_amount']-(float)$l['paid_amount']);$default=min($balance,(float)$l['monthly_deduction']);
        if($kind==='AUTO'){
            db()->prepare("DELETE FROM loan_monthly_deductions WHERE loan_id=? AND pay_month=? AND status<>'Posted'")->execute([$loanId,$pm]);
            audit('RESET','loan_monthly_deduction',$loanId.'-'.$pm,'Monthly deduction reset to automatic amount');
        }else{
            if(!in_array($kind,['OVERRIDE','SKIP','MANUAL'],true))$kind='OVERRIDE';
            if($kind==='SKIP')$amount=0;
            if($kind!=='SKIP'&&$amount<=0)throw new RuntimeException('Enter the deduction amount.');
            $amount=min($amount,$balance);
            if($reason==='')throw new RuntimeException('Reason is required for monthly amendment / manual deduction.');
            db()->prepare("INSERT INTO loan_monthly_deductions(loan_id,pay_month,adjustment_type,amount,reason,status,updated_by,updated_at)
                VALUES(?,?,?,?,?,'Planned',?,NOW()) ON DUPLICATE KEY UPDATE adjustment_type=VALUES(adjustment_type),amount=VALUES(amount),reason=VALUES(reason),status='Planned',updated_by=VALUES(updated_by),updated_at=NOW()")
                ->execute([$loanId,$pm,$kind,$amount,$reason,user()['id']]);
            audit('UPDATE','loan_monthly_deduction',$loanId.'-'.$pm,$kind.' amount '.number_format($amount,2).' - '.$reason);
        }
        la_redirect(['tab'=>'schedule','schedule_month'=>$pm]);
    }

    if($a==='save_type'){
        $id=(int)($_POST['id']??0);$code=strtoupper(trim($_POST['code']??''));$name=trim($_POST['name']??'');
        if($code===''||$name==='')throw new RuntimeException('Loan Type code and name are required.');
        if($id){
            db()->prepare("UPDATE loan_type_master SET code=?,name=?,description=?,is_active=?,updated_by=?,updated_at=NOW() WHERE id=?")
                ->execute([$code,$name,trim($_POST['description']??''),isset($_POST['is_active'])?1:0,user()['id'],$id]);
            audit('UPDATE','loan_type',(string)$id,'Loan Type updated: '.$name);
        }else{
            db()->prepare("INSERT INTO loan_type_master(code,name,description,is_active,created_by,created_at) VALUES(?,?,?,?,?,NOW())")
                ->execute([$code,$name,trim($_POST['description']??''),isset($_POST['is_active'])?1:0,user()['id']]);
            audit('SAVE','loan_type',$code,'Loan Type created');
        }
        $_SESSION['flash']='Loan Type saved.';la_redirect(['tab'=>'types']);
    }

    if($a==='delete_type'){
        $id=(int)$_POST['id'];
        $s=db()->prepare("SELECT COUNT(*) FROM staff_loans WHERE loan_type_id=?");$s->execute([$id]);
        if((int)$s->fetchColumn()>0){
            db()->prepare("UPDATE loan_type_master SET is_active=0,updated_by=?,updated_at=NOW() WHERE id=?")->execute([user()['id'],$id]);
            $_SESSION['flash']='Loan Type is already used, so it was deactivated instead of deleted.';
            audit('ARCHIVE','loan_type',(string)$id,'Used Loan Type deactivated');
        }else{
            db()->prepare("DELETE FROM loan_type_master WHERE id=?")->execute([$id]);
            $_SESSION['flash']='Unused Loan Type deleted.';audit('DELETE','loan_type',(string)$id,'Unused Loan Type deleted');
        }
        la_redirect(['tab'=>'types']);
    }

    if($a==='save_purpose'){
        $id=(int)($_POST['id']??0);$code=strtoupper(trim($_POST['code']??''));$name=trim($_POST['name']??'');
        if($code===''||$name==='')throw new RuntimeException('Purpose code and name are required.');
        if($id){
            db()->prepare("UPDATE loan_purpose_master SET code=?,name=?,description=?,is_active=?,updated_by=?,updated_at=NOW() WHERE id=?")
                ->execute([$code,$name,trim($_POST['description']??''),isset($_POST['is_active'])?1:0,user()['id'],$id]);
            audit('UPDATE','loan_purpose',(string)$id,'Loan Purpose updated: '.$name);
        }else{
            db()->prepare("INSERT INTO loan_purpose_master(code,name,description,is_active,created_by,created_at) VALUES(?,?,?,?,?,NOW())")
                ->execute([$code,$name,trim($_POST['description']??''),isset($_POST['is_active'])?1:0,user()['id']]);
            audit('SAVE','loan_purpose',$code,'Loan Purpose created');
        }
        $_SESSION['flash']='Loan Purpose saved.';la_redirect(['tab'=>'purposes']);
    }

    if($a==='delete_purpose'){
        $id=(int)$_POST['id'];$s=db()->prepare("SELECT COUNT(*) FROM staff_loans WHERE purpose_id=?");$s->execute([$id]);
        if((int)$s->fetchColumn()>0){
            db()->prepare("UPDATE loan_purpose_master SET is_active=0,updated_by=?,updated_at=NOW() WHERE id=?")->execute([user()['id'],$id]);
            $_SESSION['flash']='Purpose is already used, so it was deactivated instead of deleted.';
            audit('ARCHIVE','loan_purpose',(string)$id,'Used Loan Purpose deactivated');
        }else{
            db()->prepare("DELETE FROM loan_purpose_master WHERE id=?")->execute([$id]);
            $_SESSION['flash']='Unused Purpose deleted.';audit('DELETE','loan_purpose',(string)$id,'Unused Loan Purpose deleted');
        }
        la_redirect(['tab'=>'purposes']);
    }
}

$deps=db()->query("SELECT DISTINCT department FROM employees WHERE department<>'' ORDER BY department")->fetchAll(PDO::FETCH_COLUMN);
$emps=db()->query("SELECT employee_id,name,department FROM employees WHERE status='Active' ORDER BY name")->fetchAll();
$loanTypes=db()->query("SELECT * FROM loan_type_master ORDER BY is_active DESC,name")->fetchAll();
$loanPurposes=db()->query("SELECT * FROM loan_purpose_master ORDER BY is_active DESC,name")->fetchAll();
$activeLoanTypes=array_values(array_filter($loanTypes,fn($x)=>(int)$x['is_active']===1));
$activePurposes=array_values(array_filter($loanPurposes,fn($x)=>(int)$x['is_active']===1));

$where=["l.is_archived=0"];$params=[];
if($search!==''){$where[]="(l.employee_id LIKE ? OR e.name LIKE ? OR l.reference_no LIKE ? OR l.purpose_text LIKE ?)";$v='%'.$search.'%';array_push($params,$v,$v,$v,$v);}
if($status!==''){$where[]="l.status=?";$params[]=$status;}
if($type!==''){$where[]="COALESCE(lt.name,l.loan_type)=?";$params[]=$type;}
if($purpose!==''){$where[]="COALESCE(lp.name,l.purpose_text)=?";$params[]=$purpose;}
if($dept!==''){$where[]="e.department=?";$params[]=$dept;}
$sql="SELECT l.*,e.name,e.department,lt.name loan_type_name,lp.name purpose_name,
    COALESCE((SELECT SUM(r.amount) FROM loan_repayments r WHERE r.loan_id=l.id),0) paid_amount,
    COALESCE((SELECT COUNT(*) FROM loan_documents d WHERE d.loan_id=l.id),0) document_count
    FROM staff_loans l JOIN employees e ON e.employee_id=l.employee_id
    LEFT JOIN loan_type_master lt ON lt.id=l.loan_type_id
    LEFT JOIN loan_purpose_master lp ON lp.id=l.purpose_id
    WHERE ".implode(' AND ',$where)." ORDER BY FIELD(l.status,'Active','Suspended','Settled','Cancelled'),e.name,l.loan_date";
$s=db()->prepare($sql);$s->execute($params);$loans=$s->fetchAll();

$summary=['active'=>0,'original'=>0.0,'paid'=>0.0,'outstanding'=>0.0,'monthly'=>0.0];
foreach($loans as &$l){
    $l['balance']=max(0,(float)$l['original_amount']-(float)$l['paid_amount']);
    if($l['status']==='Active'){$summary['active']++;$summary['monthly']+=min((float)$l['monthly_deduction'],$l['balance']);}
    $summary['original']+=(float)$l['original_amount'];$summary['paid']+=(float)$l['paid_amount'];$summary['outstanding']+=$l['balance'];
}unset($l);

$detail=null;$repayments=[];$documents=[];
if($viewId||$editId){
    $id=$viewId?:$editId;
    $s=db()->prepare("SELECT l.*,e.name,e.department,lt.name loan_type_name,lp.name purpose_name,
        COALESCE((SELECT SUM(r.amount) FROM loan_repayments r WHERE r.loan_id=l.id),0) paid_amount
        FROM staff_loans l JOIN employees e ON e.employee_id=l.employee_id
        LEFT JOIN loan_type_master lt ON lt.id=l.loan_type_id LEFT JOIN loan_purpose_master lp ON lp.id=l.purpose_id
        WHERE l.id=?");
    $s->execute([$id]);$detail=$s->fetch();
    if($detail){
        $detail['balance']=max(0,(float)$detail['original_amount']-(float)$detail['paid_amount']);
        $s=db()->prepare("SELECT r.*,u.display_name FROM loan_repayments r LEFT JOIN users u ON u.id=r.posted_by WHERE r.loan_id=? ORDER BY r.payment_date,r.id");
        $s->execute([$id]);$repayments=$s->fetchAll();
        $s=db()->prepare("SELECT d.*,u.display_name FROM loan_documents d LEFT JOIN users u ON u.id=d.uploaded_by WHERE d.loan_id=? ORDER BY d.uploaded_at DESC");
        $s->execute([$id]);$documents=$s->fetchAll();
    }
}
$edit=$editId?$detail:null;

$viewType=$editType=null;
if($viewTypeId||$editTypeId){$s=db()->prepare("SELECT * FROM loan_type_master WHERE id=?");$s->execute([$viewTypeId?:$editTypeId]);$x=$s->fetch();if($viewTypeId)$viewType=$x;else$editType=$x;}
$viewPurpose=$editPurpose=null;
if($viewPurposeId||$editPurposeId){$s=db()->prepare("SELECT * FROM loan_purpose_master WHERE id=?");$s->execute([$viewPurposeId?:$editPurposeId]);$x=$s->fetch();if($viewPurposeId)$viewPurpose=$x;else$editPurpose=$x;}

render_header('Loan & Advance');flash();
?>
<style>
.loan-summary{display:grid;grid-template-columns:repeat(5,minmax(150px,1fr));gap:10px}
.loan-actions{display:flex;gap:6px;flex-wrap:wrap}.loan-actions form{display:inline}
.loan-docs{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:8px}
.loan-doc{border:1px solid #dbe3ed;border-radius:10px;padding:10px;background:#f8fafc}
.master-view{border:1px solid #dbe3ed;border-radius:10px;padding:14px;margin-bottom:12px;background:#f8fafc}
@media(max-width:900px){.loan-summary{grid-template-columns:1fr 1fr}}
@media print{.no-print,.sidebar,.topbar,.subtabs{display:none!important}.content{padding:0!important}@page{size:landscape;margin:8mm}}
</style>

<div class="hero"><h2>Loan & Advance</h2><p>Loan register, repayment history, purpose, supporting documents and loan-specific master settings in one module.</p></div>

<div class="subtabs no-print">
<a class="<?=$tab==='register'?'active':''?>" href="?tab=register">Loan Register</a>
<a class="<?=$tab==='schedule'?'active':''?>" href="?tab=schedule&schedule_month=<?=e($scheduleMonth)?>">Monthly Deduction Schedule</a>
<a class="<?=$tab==='history'?'active':''?>" href="?tab=history">Repayment History</a>
<a href="payroll_master.php?tab=loan_types">Loan Settings</a>
</div>

<?php if($tab==='schedule'):?>
<?php
$sch=db()->prepare("SELECT l.*,e.name,e.department,lt.name loan_type_name,
  COALESCE((SELECT SUM(r.amount) FROM loan_repayments r WHERE r.loan_id=l.id),0) paid_amount,
  d.adjustment_type,d.amount planned_amount,d.reason,d.status schedule_status
  FROM staff_loans l JOIN employees e ON e.employee_id=l.employee_id LEFT JOIN loan_type_master lt ON lt.id=l.loan_type_id
  LEFT JOIN loan_monthly_deductions d ON d.loan_id=l.id AND d.pay_month=?
  WHERE l.is_archived=0 AND l.status='Active' AND l.deduction_start_month<=? ORDER BY e.department,e.name,l.loan_date");
$sch->execute([$scheduleMonth,$scheduleMonth]);$scheduleRows=$sch->fetchAll();
?>
<div class="card no-print"><form method="get" class="toolbar"><input type="hidden" name="tab" value="schedule"><label><small>Pay Month</small><input type="month" name="schedule_month" value="<?=e($scheduleMonth)?>"></label><button>Open Month</button></form></div>
<div class="card"><h3>Monthly Loan Deduction Schedule — <?=e(date('F Y',strtotime($scheduleMonth.'-01')))?></h3><div class="notice">AUTO loans use the standard monthly amount unless amended here. MANUAL loans deduct only when a monthly amount is entered.</div>
<div class="tablewrap"><table><tr><th>Employee</th><th>Department</th><th>Loan</th><th>Method</th><th>Outstanding</th><th>Standard</th><th>Current Month</th><th>Control</th><th>Reason</th><th>Status</th></tr>
<?php foreach($scheduleRows as $r):
$bal=max(0,(float)$r['original_amount']-(float)$r['paid_amount']);$default=min($bal,(float)$r['monthly_deduction']);
$method=$r['deduction_method']??'AUTO';$adj=$r['adjustment_type']??'';$actual=$method==='MANUAL'?0:$default;
if($adj==='SKIP')$actual=0;elseif(in_array($adj,['OVERRIDE','MANUAL','EXCEL'],true))$actual=(float)$r['planned_amount'];
?>
<tr><td><b><?=e($r['name'])?></b><br><?=e($r['employee_id'])?></td><td><?=e($r['department'])?></td><td><?=e($r['loan_type_name']?:$r['loan_type'])?></td><td><?=$method==='AUTO'?'Auto Monthly':'Manual by Month'?></td><td><?=money($bal)?></td><td><?=money($default)?></td><td><b><?=money($actual)?></b></td>
<td class="no-print"><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="save_monthly_deduction"><input type="hidden" name="loan_id" value="<?=$r['id']?>"><input type="hidden" name="pay_month" value="<?=e($scheduleMonth)?>">
<select name="adjustment_type"><option value="AUTO">Use Standard / Reset</option><option value="OVERRIDE" <?=$adj==='OVERRIDE'?'selected':''?>>Override Amount</option><option value="SKIP" <?=$adj==='SKIP'?'selected':''?>>Skip This Month</option><option value="MANUAL" <?=$adj==='MANUAL'?'selected':''?>>Manual Payment This Month</option></select>
<input type="number" step="0.01" min="0" name="amount" value="<?=e(in_array($adj,['OVERRIDE','MANUAL'],true)?$r['planned_amount']:'')?>" placeholder="Final amount"><input name="reason" value="<?=e($r['reason']??'')?>" placeholder="Reason"><button>Save</button></form></td>
<td><?=e($r['reason']??'')?></td><td><?=e($r['schedule_status']??'Planned')?></td></tr><?php endforeach;?>
<?php if(!$scheduleRows):?><tr><td colspan="10">No active loans are due for this month.</td></tr><?php endif;?></table></div></div>

<?php elseif($tab==='history'):?>
<?php
$hs=db()->query("SELECT r.*,l.loan_type,l.reference_no,e.employee_id,e.name,e.department,u.display_name
 FROM loan_repayments r JOIN staff_loans l ON l.id=r.loan_id JOIN employees e ON e.employee_id=l.employee_id LEFT JOIN users u ON u.id=r.posted_by
 ORDER BY r.payment_date DESC,r.id DESC LIMIT 500");$historyRows=$hs->fetchAll();
?>
<div class="card"><h3>Loan Repayment History</h3><div class="tablewrap"><table><tr><th>Pay Month</th><th>Date</th><th>Employee</th><th>Department</th><th>Loan</th><th>Source</th><th>Amount</th><th>Reference</th><th>Posted By</th><th>Payroll Link</th></tr>
<?php foreach($historyRows as $r):?><tr><td><?=e($r['pay_month']?:'Manual')?></td><td><?=e($r['payment_date'])?></td><td><b><?=e($r['name'])?></b><br><?=e($r['employee_id'])?></td><td><?=e($r['department'])?></td><td><?=e($r['loan_type'])?></td><td><?=e($r['source'])?></td><td><?=money($r['amount'])?></td><td><?=e($r['reference_no'])?></td><td><?=e($r['display_name']??'')?></td><td><?php if($r['pay_month']):?><a class="btn" href="payroll.php?month=<?=e($r['pay_month'])?>">Open <?=e(date('M Y',strtotime($r['pay_month'].'-01')))?></a><?php else:?>—<?php endif;?></td></tr><?php endforeach;?>
<?php if(!$historyRows):?><tr><td colspan="10">No repayment history.</td></tr><?php endif;?></table></div></div>

<?php elseif($tab==='types'):?>
<?php if($viewType):?><div class="master-view"><h3><?=e($viewType['name'])?></h3><p><b>Code:</b> <?=e($viewType['code'])?> · <b>Status:</b> <?=$viewType['is_active']?'Active':'Inactive'?></p><p><?=e($viewType['description']?:'No description')?></p><a class="btn no-print" href="?tab=types&edit_type=<?=$viewType['id']?>">Edit</a> <a class="btn no-print" href="?tab=types">Close</a></div><?php endif;?>
<div class="card no-print"><div class="profilehead"><div><h3>Loan Type Master</h3><div class="profilemeta">Add / Edit / Delete or Deactivate / View / Print / Export / Filter / Search.</div></div><div class="loan-actions"><button onclick="window.print()">Print</button><a class="btn green" href="loan_master_export.php?<?=e(http_build_query(['master'=>'types','search'=>$search,'master_status'=>$masterStatus]))?>">Export</a></div></div>
<form method="get" class="toolbar"><input type="hidden" name="tab" value="types"><input name="search" value="<?=e($search)?>" placeholder="Search code / name / description"><select name="master_status"><option value="">All Status</option><option value="Active" <?=$masterStatus==='Active'?'selected':''?>>Active</option><option value="Inactive" <?=$masterStatus==='Inactive'?'selected':''?>>Inactive</option></select><button>Filter / Search</button><a class="btn" href="?tab=types">Reset</a></form></div>
<div class="card no-print"><h3><?=$editType?'Edit':'Add'?> Loan Type</h3><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="save_type"><input type="hidden" name="id" value="<?=e($editType['id']??0)?>">
<div class="formgrid"><label><small>Code</small><input name="code" value="<?=e($editType['code']??'')?>" required></label><label><small>Loan Type Name</small><input name="name" value="<?=e($editType['name']??'')?>" required></label><label class="wide"><small>Description</small><input name="description" value="<?=e($editType['description']??'')?>"></label><label><input type="checkbox" style="width:auto" name="is_active" <?=!$editType||$editType['is_active']?'checked':''?>> Active</label></div>
<button class="primary">Save Loan Type</button><?php if($editType):?> <a class="btn" href="?tab=types">Cancel</a><?php endif;?></form></div>
<div class="card"><div class="tablewrap"><table><tr><th>Code</th><th>Loan Type</th><th>Description</th><th>Status</th><th class="no-print">Action</th></tr>
<?php foreach($loanTypes as $r):
if($search!==''&&!str_contains(strtolower($r['code'].' '.$r['name'].' '.$r['description']),strtolower($search)))continue;
if($masterStatus==='Active'&&!$r['is_active'])continue;if($masterStatus==='Inactive'&&$r['is_active'])continue;?><tr><td><?=e($r['code'])?></td><td><b><?=e($r['name'])?></b></td><td><?=e($r['description'])?></td><td><?=$r['is_active']?'Active':'Inactive'?></td><td class="no-print"><a class="btn" href="?tab=types&view_type=<?=$r['id']?>">View</a> <a class="btn" href="?tab=types&edit_type=<?=$r['id']?>">Edit</a> <form method="post" style="display:inline" onsubmit="return confirm('Delete this Loan Type? Used types will be deactivated instead.')"><?=csrf_field()?><input type="hidden" name="action" value="delete_type"><input type="hidden" name="id" value="<?=$r['id']?>"><button class="red btn">Delete</button></form></td></tr><?php endforeach;?></table></div></div>

<?php elseif($tab==='purposes'):?>
<?php if($viewPurpose):?><div class="master-view"><h3><?=e($viewPurpose['name'])?></h3><p><b>Code:</b> <?=e($viewPurpose['code'])?> · <b>Status:</b> <?=$viewPurpose['is_active']?'Active':'Inactive'?></p><p><?=e($viewPurpose['description']?:'No description')?></p><a class="btn no-print" href="?tab=purposes&edit_purpose=<?=$viewPurpose['id']?>">Edit</a> <a class="btn no-print" href="?tab=purposes">Close</a></div><?php endif;?>
<div class="card no-print"><div class="profilehead"><div><h3>Purpose Master</h3><div class="profilemeta">Standardise loan purposes while still allowing an Other Purpose entry.</div></div><div class="loan-actions"><button onclick="window.print()">Print</button><a class="btn green" href="loan_master_export.php?<?=e(http_build_query(['master'=>'purposes','search'=>$search,'master_status'=>$masterStatus]))?>">Export</a></div></div>
<form method="get" class="toolbar"><input type="hidden" name="tab" value="purposes"><input name="search" value="<?=e($search)?>" placeholder="Search code / purpose / description"><select name="master_status"><option value="">All Status</option><option value="Active" <?=$masterStatus==='Active'?'selected':''?>>Active</option><option value="Inactive" <?=$masterStatus==='Inactive'?'selected':''?>>Inactive</option></select><button>Filter / Search</button><a class="btn" href="?tab=purposes">Reset</a></form></div>
<div class="card no-print"><h3><?=$editPurpose?'Edit':'Add'?> Purpose</h3><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="save_purpose"><input type="hidden" name="id" value="<?=e($editPurpose['id']??0)?>">
<div class="formgrid"><label><small>Code</small><input name="code" value="<?=e($editPurpose['code']??'')?>" required></label><label><small>Purpose Name</small><input name="name" value="<?=e($editPurpose['name']??'')?>" required></label><label class="wide"><small>Description</small><input name="description" value="<?=e($editPurpose['description']??'')?>"></label><label><input type="checkbox" style="width:auto" name="is_active" <?=!$editPurpose||$editPurpose['is_active']?'checked':''?>> Active</label></div>
<button class="primary">Save Purpose</button><?php if($editPurpose):?> <a class="btn" href="?tab=purposes">Cancel</a><?php endif;?></form></div>
<div class="card"><div class="tablewrap"><table><tr><th>Code</th><th>Purpose</th><th>Description</th><th>Status</th><th class="no-print">Action</th></tr>
<?php foreach($loanPurposes as $r):
if($search!==''&&!str_contains(strtolower($r['code'].' '.$r['name'].' '.$r['description']),strtolower($search)))continue;
if($masterStatus==='Active'&&!$r['is_active'])continue;if($masterStatus==='Inactive'&&$r['is_active'])continue;?><tr><td><?=e($r['code'])?></td><td><b><?=e($r['name'])?></b></td><td><?=e($r['description'])?></td><td><?=$r['is_active']?'Active':'Inactive'?></td><td class="no-print"><a class="btn" href="?tab=purposes&view_purpose=<?=$r['id']?>">View</a> <a class="btn" href="?tab=purposes&edit_purpose=<?=$r['id']?>">Edit</a> <form method="post" style="display:inline" onsubmit="return confirm('Delete this Purpose? Used purposes will be deactivated instead.')"><?=csrf_field()?><input type="hidden" name="action" value="delete_purpose"><input type="hidden" name="id" value="<?=$r['id']?>"><button class="red btn">Delete</button></form></td></tr><?php endforeach;?></table></div></div>

<?php else:?>
<div class="card no-print"><form method="get" class="report-filter"><input type="hidden" name="tab" value="register">
<label><small>Search</small><input name="search" value="<?=e($search)?>" placeholder="Employee / ID / reference / purpose"></label>
<label><small>Status</small><select name="status"><option value="">All Status</option><?php foreach(['Active','Suspended','Settled','Cancelled'] as $x):?><option <?=$status===$x?'selected':''?>><?=$x?></option><?php endforeach;?></select></label>
<label><small>Loan Type</small><select name="type"><option value="">All Types</option><?php foreach($loanTypes as $x):?><option value="<?=e($x['name'])?>" <?=$type===$x['name']?'selected':''?>><?=e($x['name'])?></option><?php endforeach;?></select></label>
<label><small>Purpose</small><select name="purpose"><option value="">All Purposes</option><?php foreach($loanPurposes as $x):?><option value="<?=e($x['name'])?>" <?=$purpose===$x['name']?'selected':''?>><?=e($x['name'])?></option><?php endforeach;?></select></label>
<label><small>Department</small><select name="department"><option value="">All Departments</option><?php foreach($deps as $d):?><option <?=$dept===$d?'selected':''?>><?=e($d)?></option><?php endforeach;?></select></label>
<button class="primary">Filter</button><a class="btn" href="loan_advance.php?tab=register">Reset</a></form>
<div class="toolbar"><button onclick="window.print()">Print</button><a class="btn green" href="loan_advance_export.php?<?=e(http_build_query(['search'=>$search,'status'=>$status,'type'=>$type,'purpose'=>$purpose,'department'=>$dept]))?>">Export</a></div></div>

<div class="loan-summary">
<div class="card kpi"><b><?=$summary['active']?></b><small>Active Loans</small></div>
<div class="card kpi"><b><?=money($summary['original'])?></b><small>Original Amount</small></div>
<div class="card kpi"><b><?=money($summary['paid'])?></b><small>Total Repaid</small></div>
<div class="card kpi"><b><?=money($summary['outstanding'])?></b><small>Outstanding</small></div>
<div class="card kpi"><b><?=money($summary['monthly'])?></b><small>Next Monthly Deductions</small></div>
</div>

<?php if($detail && $viewId):?>
<div class="card">
<div class="profilehead"><div><h3><?=e($detail['name'])?> — <?=e($detail['loan_type_name']?:$detail['loan_type'])?></h3><div class="profilemeta"><?=e($detail['employee_id'])?> · <?=e($detail['department'])?> · Reference <?=e($detail['reference_no']?:'—')?></div></div><a class="btn no-print" href="loan_advance.php?tab=register&edit=<?=$detail['id']?>">Edit</a></div>
<div class="grid"><div><small>Purpose</small><b><?=e($detail['purpose_name']?:$detail['purpose_text']?:'—')?></b></div><div><small>Original</small><b><?=money($detail['original_amount'])?></b></div><div><small>Paid</small><b><?=money($detail['paid_amount'])?></b></div><div><small>Outstanding</small><b><?=money($detail['balance'])?></b></div><div><small>Monthly Deduction</small><b><?=money($detail['monthly_deduction'])?></b></div><div><small>Start</small><b><?=e($detail['deduction_start_month'])?></b></div><div><small>Expected Completion</small><b><?=e($detail['expected_completion_month']?:'—')?></b></div><div><small>Status</small><b><?=e($detail['status'])?></b></div></div>
<?php if($detail['remarks']):?><p><?=nl2br(e($detail['remarks']))?></p><?php endif;?>
</div>

<div class="card"><h3>Supporting Documents</h3><div class="loan-docs">
<?php foreach($documents as $d):?><div class="loan-doc"><b><?=e($d['original_name'])?></b><br><span class="subtle"><?=number_format($d['file_size']/1024,1)?> KB · <?=e($d['uploaded_at'])?></span><div class="loan-actions no-print" style="margin-top:8px"><a class="btn" href="loan_document.php?id=<?=$d['id']?>">View</a><a class="btn" href="loan_document.php?id=<?=$d['id']?>&download=1">Download</a><form method="post" onsubmit="return confirm('Delete this supporting document?')"><?=csrf_field()?><input type="hidden" name="action" value="delete_document"><input type="hidden" name="loan_id" value="<?=$detail['id']?>"><input type="hidden" name="document_id" value="<?=$d['id']?>"><button class="red btn">Delete</button></form></div></div><?php endforeach;?>
<?php if(!$documents):?><div class="subtle">No supporting documents attached.</div><?php endif;?>
</div></div>

<div class="card"><h3>Repayment History</h3><div class="tablewrap"><table><tr><th>Date</th><th>Payroll Month</th><th>Source</th><th>Reference</th><th>Amount</th><th>Posted By</th><th>Remarks</th><th class="no-print"></th></tr>
<?php foreach($repayments as $r):?><tr><td><?=e($r['payment_date'])?></td><td><?=e($r['pay_month']?:'—')?></td><td><?=e($r['source'])?></td><td><?=e($r['reference_no'])?></td><td><?=money($r['amount'])?></td><td><?=e($r['display_name']??'')?></td><td><?=e($r['remarks'])?></td><td class="no-print"><?php if($r['source']==='Manual'):?><form method="post" onsubmit="return confirm('Delete this manual repayment?')"><?=csrf_field()?><input type="hidden" name="action" value="delete_manual_repayment"><input type="hidden" name="loan_id" value="<?=$detail['id']?>"><input type="hidden" name="repayment_id" value="<?=$r['id']?>"><button class="red btn">Delete</button></form><?php endif;?></td></tr><?php endforeach;?>
<?php if(!$repayments):?><tr><td colspan="8">No repayment posted yet.</td></tr><?php endif;?></table></div></div>

<?php if($detail['balance']>0 && $detail['status']!=='Cancelled'):?>
<div class="card no-print"><h3>Post Manual Repayment</h3><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="manual_repayment"><input type="hidden" name="loan_id" value="<?=$detail['id']?>">
<div class="formgrid"><label><small>Payment Date</small><input type="date" name="payment_date" value="<?=date('Y-m-d')?>" required></label><label><small>Amount</small><input type="number" step="0.01" min="0.01" max="<?=e($detail['balance'])?>" name="amount" required></label><label><small>Reference</small><input name="reference_no"></label><label><small>Remarks</small><input name="remarks"></label></div><button class="primary">Post Repayment</button></form></div>
<?php endif;?>
<?php endif;?>

<div class="card no-print"><h3><?=$edit?'Edit':'New'?> Loan / Advance</h3><form method="post" enctype="multipart/form-data"><?=csrf_field()?><input type="hidden" name="action" value="save_loan"><input type="hidden" name="id" value="<?=e($edit['id']??0)?>">
<div class="formgrid">
<label><small>Employee</small><input name="employee_id" list="loanEmp" value="<?=e($edit['employee_id']??'')?>" required><datalist id="loanEmp"><?php foreach($emps as $e):?><option value="<?=e($e['employee_id'])?>"><?=e($e['name'].' — '.$e['department'])?></option><?php endforeach;?></datalist></label>
<label><small>Loan Type</small><select name="loan_type_id" required><option value="">Select Loan Type</option><?php foreach($activeLoanTypes as $x):?><option value="<?=$x['id']?>" <?=($edit['loan_type_id']??0)==$x['id']?'selected':''?>><?=e($x['name'])?></option><?php endforeach;?></select></label>
<label><small>Purpose</small><select name="purpose_id"><option value="">Other / Enter Below</option><?php foreach($activePurposes as $x):?><option value="<?=$x['id']?>" <?=($edit['purpose_id']??0)==$x['id']?'selected':''?>><?=e($x['name'])?></option><?php endforeach;?></select></label>
<label><small>Other Purpose</small><input name="purpose_text" value="<?=e($edit['purpose_text']??'')?>" placeholder="Required if no master purpose selected"></label>
<label><small>Loan Date</small><input type="date" name="loan_date" value="<?=e($edit['loan_date']??date('Y-m-d'))?>" required></label>
<label><small>Original Amount</small><input type="number" step="0.01" min="0.01" name="original_amount" value="<?=e($edit['original_amount']??'')?>" required></label>
<label><small>Monthly Deduction</small><input type="number" step="0.01" min="0.01" name="monthly_deduction" value="<?=e($edit['monthly_deduction']??'')?>" required></label>
<label><small>Deduction Method</small><select name="deduction_method"><option value="AUTO" <?=($edit['deduction_method']??'AUTO')==='AUTO'?'selected':''?>>Auto Monthly — amendable by month</option><option value="MANUAL" <?=($edit['deduction_method']??'')==='MANUAL'?'selected':''?>>Manual by Month</option></select></label>
<label><small>Deduction Start Month</small><input type="month" name="deduction_start_month" value="<?=e($edit['deduction_start_month']??date('Y-m'))?>" required></label>
<label><small>Expected Completion (optional)</small><input type="month" name="expected_completion_month" value="<?=e($edit['expected_completion_month']??'')?>"></label>
<label><small>Reference No.</small><input name="reference_no" value="<?=e($edit['reference_no']??'')?>"></label>
<label class="wide"><small>Supporting Documents</small><input type="file" name="attachments[]" multiple accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx"><span class="subtle">PDF, image, Word or Excel. Maximum 10 MB per file. Multiple attachments allowed.</span></label>
<label class="wide"><small>Remarks</small><input name="remarks" value="<?=e($edit['remarks']??'')?>"></label>
</div><button class="primary"><?=$edit?'Save Changes':'Create Loan / Advance'?></button><?php if($edit):?> <a class="btn" href="loan_advance.php?tab=register&view=<?=$edit['id']?>">Cancel</a><?php endif;?></form></div>

<div class="card"><h3>Loan / Advance Register</h3><div class="tablewrap"><table>
<tr><th>Employee</th><th>Department</th><th>Type</th><th>Purpose</th><th>Original</th><th>Paid</th><th>Outstanding</th><th>Monthly</th><th>Method</th><th>Start</th><th>Expected End</th><th>Status</th><th>Docs</th><th>Reference</th><th class="no-print">Action</th></tr>
<?php foreach($loans as $l):?><tr><td><b><?=e($l['name'])?></b><br><span class="subtle"><?=e($l['employee_id'])?></span></td><td><?=e($l['department'])?></td><td><?=e($l['loan_type_name']?:$l['loan_type'])?></td><td><?=e($l['purpose_name']?:$l['purpose_text']?:'—')?></td><td><?=money($l['original_amount'])?></td><td><?=money($l['paid_amount'])?></td><td><b><?=money($l['balance'])?></b></td><td><?=money($l['monthly_deduction'])?></td><td><?=($l['deduction_method']??'AUTO')==='AUTO'?'Auto / Amendable':'Manual by Month'?></td><td><?=e($l['deduction_start_month'])?></td><td><?=e($l['expected_completion_month']?:'—')?></td><td><span class="badge <?=$l['status']==='Active'?'green':($l['status']==='Suspended'?'amber':'')?>"><?=e($l['status'])?></span></td><td><?=$l['document_count']?></td><td><?=e($l['reference_no'])?></td>
<td class="no-print"><div class="loan-actions"><a class="btn" href="?tab=register&view=<?=$l['id']?>">View</a><a class="btn" href="?tab=register&edit=<?=$l['id']?>">Edit</a><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="status"><input type="hidden" name="id" value="<?=$l['id']?>"><select name="loan_status" onchange="this.form.submit()"><?php foreach(['Active','Suspended','Settled','Cancelled'] as $x):?><option <?=$l['status']===$x?'selected':''?>><?=$x?></option><?php endforeach;?></select></form><form method="post" onsubmit="return confirm('Delete/archive this loan?')"><?=csrf_field()?><input type="hidden" name="action" value="archive"><input type="hidden" name="id" value="<?=$l['id']?>"><button class="red btn">Delete / Archive</button></form></div></td></tr><?php endforeach;?>
<?php if(!$loans):?><tr><td colspan="15">No loan / advance records found.</td></tr><?php endif;?></table></div></div>
<?php endif;?>
<?php render_footer(); ?>