<?php
/* /edenrms/pages/receipt.php — EDEN receipt (18cm × 10.5cm, landscape) */
/* Works even if some column names differ (payment_method/method, batch_name/code/name, etc.) */

/* Try app connection first if available */
$mysqli = null;
@include_once __DIR__ . '/../includes/db.php';
if (isset($conn) && $conn instanceof mysqli) {
  $mysqli = $conn;
} else {
  /* Fallback: try both common DB names */
  $mysqli = @new mysqli("localhost","root","","edencamp_edencampus");
  if ($mysqli->connect_error) { $mysqli = @new mysqli("localhost","root","","edencampus"); }
}
if ($mysqli && !$mysqli->connect_error) { $mysqli->set_charset("utf8mb4"); }

if ($payload['branch_name'] === '')  $payload['branch_name'] = 'Main';
if ($payload['cashier_name'] === '') $payload['cashier_name'] = '-';

/* helpers */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function nf($n){ return number_format((float)$n,2); }
function q($k,$d=''){ return isset($_GET[$k]) ? trim((string)$_GET[$k]) : $d; }
function tableExists(mysqli $db,string $t): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
  $st->bind_param('s',$t); $st->execute(); $st->store_result();
  $ok=$st->num_rows>0; $st->free_result(); $st->close(); return $ok;
}
function colExists(mysqli $db,string $t,string $c): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param('ss',$t,$c); $st->execute(); $st->store_result();
  $ok=$st->num_rows>0; $st->free_result(); $st->close(); return $ok;
}

/* read id */
$payment_id = (int)(q('payment_id') ?: q('id') ?: 0);

/* Defaults so you can also open like:
   receipt.php?student_name=Manoj&course_name=L4%20Diploma&amount=15000&payment_method=Cash&bill_ref=P00010&reg_no=NEC-209&serial=0010
*/
$payload = [
  'date_paid'      => q('date_paid',''),
  'student_name'   => q('student_name',''),
  'course_name'    => q('course_name',''),
  'batch_code'     => q('batch_code',''),
  'amount'         => q('amount',''),
  'payment_method' => q('payment_method',''),
  'bill_ref'       => q('bill_ref',''),
  'reg_no'         => q('reg_no',''),
  'serial'         => q('serial',''),
  'branch_name'    => q('branch_name',''),
  'cashier_name'   => q('cashier_name',''),
];
/* Load from DB if payment_id is given and DB is available */
if ($payment_id > 0 && $mysqli && !$mysqli->connect_error) {
  /* map flexible payment columns */
  $ptbl = 'payments';
  $c_amount = colExists($mysqli,$ptbl,'amount') ? 'amount' : null;
  $c_method = colExists($mysqli,$ptbl,'payment_method') ? 'payment_method' : (colExists($mysqli,$ptbl,'method') ? 'method' : null);
  $c_date   = colExists($mysqli,$ptbl,'date_paid') ? 'date_paid' : (colExists($mysqli,$ptbl,'created_at') ? 'created_at' : null);
  $c_ref    = colExists($mysqli,$ptbl,'reference_no') ? 'reference_no' : (colExists($mysqli,$ptbl,'ref_no') ? 'ref_no' : null);
  $c_sid    = colExists($mysqli,$ptbl,'student_id') ? 'student_id' : null;

  $c_branch = colExists($mysqli,$ptbl,'branch_name') ? 'branch_name' : null;
  $c_cashier= colExists($mysqli,$ptbl,'cashier_name') ? 'cashier_name' : null;

  $st = $mysqli->prepare("SELECT * FROM $ptbl WHERE id=? LIMIT 1");
  $st->bind_param("i",$payment_id); $st->execute();
  $res = $st->get_result(); $pay = $res ? ($res->fetch_assoc() ?: []) : [];
  $st->close();

  $sid = ($c_sid && isset($pay[$c_sid])) ? (int)$pay[$c_sid] : 0;

  /* student */
  $stu = [];
  if ($sid>0 && tableExists($mysqli,'studentss')) {
    $st = $mysqli->prepare("SELECT * FROM studentss WHERE id=? LIMIT 1");
    $st->bind_param("i",$sid); $st->execute();
    $res=$st->get_result(); $stu = $res?($res->fetch_assoc()?:[]):[];
    $st->close();
  }

  /* batch (try enrollments→batches; else student_batches; else batch_students) */
  $batch = [];
  if ($sid>0) {
    if (tableExists($mysqli,'enrollments') && tableExists($mysqli,'batches') && colExists($mysqli,'enrollments','batch_id')) {
      $st = $mysqli->prepare("
        SELECT b.* FROM enrollments e
        JOIN batches b ON b.id = e.batch_id
        WHERE e.student_id=? ORDER BY e.id DESC LIMIT 1
      ");
      $st->bind_param("i",$sid); $st->execute();
      $res=$st->get_result(); $batch=$res?($res->fetch_assoc()?:[]):[];
      $st->close();
    }
    if (!$batch && tableExists($mysqli,'student_batches') && tableExists($mysqli,'batches')) {
      $st = $mysqli->prepare("
        SELECT b.* FROM student_batches sb
        JOIN batches b ON b.id = sb.batch_id
        WHERE sb.student_id=? ORDER BY sb.id DESC LIMIT 1
      ");
      $st->bind_param("i",$sid); $st->execute();
      $res=$st->get_result(); $batch=$res?($res->fetch_assoc()?:[]):[];
      $st->close();
    }
    if (!$batch && tableExists($mysqli,'batch_students') && tableExists($mysqli,'batches')) {
      $st = $mysqli->prepare("
        SELECT b.* FROM batch_students bs
        JOIN batches b ON b.id = bs.batch_id
        WHERE bs.student_id=? ORDER BY bs.id DESC LIMIT 1
      ");
      $st->bind_param("i",$sid); $st->execute();
      $res=$st->get_result(); $batch=$res?($res->fetch_assoc()?:[]):[];
      $st->close();
    }
  }

  /* course via batch */
  $course = [];
  $cid = isset($batch['course_id']) ? (int)$batch['course_id'] : 0;
  if ($cid>0 && tableExists($mysqli,'courses')) {
    $st = $mysqli->prepare("SELECT * FROM courses WHERE id=? LIMIT 1");
    $st->bind_param("i",$cid); $st->execute();
    $res=$st->get_result(); $course=$res?($res->fetch_assoc()?:[]):[];
    $st->close();
  }

  /* merge payload */
   $payload = array_merge($payload, [
    'date_paid'      => $payload['date_paid']      ?: ($c_date   ? ($pay[$c_date]   ?? '') : ''),
    'student_name'   => $payload['student_name']   ?: ($stu['full_name'] ?? ($stu['name'] ?? '')),
    'course_name'    => $payload['course_name']    ?: ($course['course_name'] ?? ($course['name'] ?? '')),
    'batch_code'     => $payload['batch_code']     ?: ($batch['batch_name'] ?? ($batch['code'] ?? ($batch['name'] ?? ''))),
    'amount'         => $payload['amount']         ?: ($c_amount ? ($pay[$c_amount] ?? '') : ''),
    'payment_method' => $payload['payment_method'] ?: ($c_method ? ($pay[$c_method] ?? '') : ''),
    'bill_ref'       => $payload['bill_ref']       ?: ('P'.str_pad($payment_id,5,'0',STR_PAD_LEFT)),
    'reg_no'         => $payload['reg_no']         ?: ($stu['center_reg_no'] ?? ($stu['center_registration_no'] ?? ($stu['center_no'] ?? ($stu['center_reg'] ?? '')))),
    'serial'         => $payload['serial']         ?: substr(str_pad($payment_id,4,'0',STR_PAD_LEFT),-4),

    'branch_name'    => $payload['branch_name']    ?: ($c_branch ? ($pay[$c_branch] ?? '') : ''),
    'cashier_name'   => $payload['cashier_name']   ?: ($c_cashier ? ($pay[$c_cashier] ?? '') : ''),
  ]);
}

/* Normalize method for ticks */
$pm = strtolower(preg_replace('/\s+/', '', (string)$payload['payment_method']));
$pm_cash   = in_array($pm, ['cash']);
$pm_card   = in_array($pm, ['card','cardvisa','visa','master','amex','card(v/m)','card(visa/master)']);
$pm_bank   = in_array($pm, ['banktransfer','bank','transfer']);
$pm_online = in_array($pm, ['online','web','gateway','payonline']);

/* logo path may be overridden by query */
$logo = q('logo', 'eden_logo.png');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Receipt</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /* Paper: exact landscape slip */
  @page { size: 18cm 10.5cm; margin: 4mm; }
  html,body{ height:100%; }
  body{
    font-family: Arial, Helvetica, sans-serif;
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
    margin:0;
  }

  .sheet{
    width:18cm; height:10.5cm;
    box-sizing:border-box;
    padding: 2mm 7mm;
    margin:0 auto;
    position:relative;
    border:1px solid #dcdcdc; /* remove if you don’t want a visible edge */
  }

  /* --- Header (IMAGE first, TEXT after) --- */
  .header{
    display:grid;
    grid-template-columns: 25mm 1fr; /* image column then flexible text */
    column-gap: 6mm;
    align-items:center;
  }
  .logo img{ height: 18mm; object-fit: contain; display:block; }
  .hdr-left{ text-align:left; line-height:1.2; } /* was .hdr-right in your CSS */
  .campus{ color:#1a3e85; font-weight:800; font-size:22px; letter-spacing:.2px; }
  .addr{ font-size:11px; color:#222; }
  .serial{
    position:absolute; right:10mm; top:10mm;
    display:inline-block; padding:.5mm 3mm;
    font-weight:800; color:#e40000; font-size:16px;
    background:#fff; border-radius:2px;
  }

  /* --- Thin underlined fields --- */
  .grid-top{
    display:grid;
    grid-template-columns: 1fr 1fr;
    column-gap: 45mm; row-gap: 3mm;
    margin-top: 6mm;
  }
  .pair{ display:flex; align-items:center; gap:2mm; }
  .label{ font-size:13px; font-weight:700; color:#222; min-width:max-content; }
  .uline{
    flex:1;
    border-bottom:1.6px solid #000;
    height:3mm;
    display:flex; align-items:flex-end;
    padding-bottom:1mm;
    font-size:14px; font-weight:600;
    min-width:25mm;
  }

  /* Full-width rows */
  .row{ display:flex; align-items:center; gap:4mm; margin-top: 4mm; }
  .row .label{ min-width: 40mm; }
  .row .uline{ flex: 1; }

  /* Payment method ticks */
  .methods{ display:flex; gap: 4mm; flex-wrap:wrap; }
  .method{ display:flex; align-items:center; gap:3mm; font-size:14px; font-weight:700; }
  .box{
    width:4mm; height:4mm;
    border:1.6px solid #000;
    display:flex; align-items:center; justify-content:center;
    font-weight:800; font-size:12px; line-height:1;
  }
 .sigline{
  width:60mm;
  border-bottom:1.6px solid #000;
  height:0;
  margin-top:8mm;
}

.footer{
  position:absolute;
  left:7mm;
  right:8mm;
  bottom:1mm;
}

.sig-wrap{
  width:60mm;
  margin-top:6mm;
}

.note{
  margin-top:4mm;
  font-size:11px;
  color:#333;
}

  .print-btn{ position:fixed; top:5px; left:10px; z-index:9999; }
  @media print{ .print-btn{ display:none; } .sheet{ border:0; } }
</style>
</head>
<body>
<button class="print-btn" onclick="window.print()">Print</button>

<div class="sheet">

  <!-- Header -->
  <div class="header">
    <div class="logo">
      <img src="<?= h($logo) ?>" alt="EDEN CAMPUS">
    </div>
    <div class="hdr-left">
      <div class="campus">EDEN CAMPUS NEGOMBO</div>
      <div class="addr">58/A, 2nd Floor, St. Joseph Street, Negombo, Sri Lanka</div>
      <div class="addr">031 228 3 228 | 0777 430 703 | 0775 353 526</div>
      <div class="addr">info@edencampus.lk &nbsp; | &nbsp; www.edencampus.lk</div>
      <div class="serial"><?= h($payload['serial'] ?: '0000') ?></div>
    </div>
  </div>

  <!-- Top paired lines -->
  <div class="grid-top">
    <div class="pair">
      <div class="label">Date:</div>
      <div class="uline" style="max-width:60mm;"><?= h($payload['date_paid'] ?: date('Y-m-d')) ?></div>
    </div>

    <div class="pair">
      <div class="label" style="margin-left:auto;">Bill Ref No:</div>
      <div class="uline" style="max-width:60mm;"><?= h($payload['bill_ref']) ?></div>
    </div>

    <div></div>
    <div class="pair">
      <div class="label" style="margin-left:auto;">Registration No:</div>
      <div class="uline" style="max-width:60mm;"><?= h($payload['reg_no']) ?></div>
    </div>
  </div>

  <!-- Student / Course -->
  <div class="row" style="margin-top:6mm;">
    <div class="label">Student Name (Mr./Ms.):</div>
    <div class="uline"><?= h($payload['student_name']) ?></div>
  </div>

  <div class="row">
    <div class="label">Course Name:</div>
    <div class="uline">
      <?= h(trim(($payload['course_name'] ? $payload['course_name'].'  ' : ''))) ?>
    </div>
  </div>
  
 

  <!-- Payment Method -->
  <div class="row">
    <div class="label">Payment Method:</div>
    <div class="methods">
      <div class="method"><span class="box"><?= $pm_cash?'✓':'' ?></span> Cash</div>
      <div class="method"><span class="box"><?= $pm_card?'✓':'' ?></span> Card</div>
      <div class="method"><span class="box"><?= $pm_bank?'✓':'' ?></span> Bank Transfer</div>
      <div class="method"><span class="box"><?= $pm_online?'✓':'' ?></span> Online</div>
    </div>
  </div>

  <!-- Amount -->
  <div class="row">
    <div class="label">Amount Paid:</div>
    <div class="uline"><?= $payload['amount']!=='' ? nf($payload['amount']) : '' ?> LKR</div>
  </div>

  <!-- Signature + note -->
<div class="footer">
  <div class="label" style="font-weight:700; color:#222;">Cashier/Admin Signature:</div>

  <div class="sig-wrap">
    <div class="sigline"></div>

    <div style="
  width:60mm;
  margin-top:3mm;
  font-size:14px;
  font-weight:700;
  color:#111;
  text-align:center;
">
  <?= h($payload['cashier_name']) ?>
</div>
  </div>

  <div class="note" style="margin-top:4mm;">
    This receipt is valid only with the official Eden Campus seal and authorized signature.<br>
    Fees once paid are non-refundable under any circumstances.
  </div>
</div>
</html>
