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

// <<< IMPORTANT: ensure everything runs in UTF-8
mb_internal_encoding('UTF-8');
if (!headers_sent()) {
  header('Content-Type: text/html; charset=UTF-8');
}

include_once('../header.php');

include_once("../config.php");
include_once("../functions.php");
include_once(ROOT_PATH . 'library/helper.php');

// Dompdf for PDF generation
require_once(ROOT_PATH . 'vendor/dompdf/autoload.inc.php');
use Dompdf\Dompdf;

// --- Localization / helpers ---
$page_name = '';
$lang_code_global = "English";
$global_currency = "$";
$currency_position = "left";
$currency_sep = ".";
$localization = array();
$cookie_name = "ams_lang_code";
$cookie_name_branch = "ams_branch_code";
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_add_fare.php');
$ams_helper = new ams_helper();

// --- Auth ---
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

// --- Branch / building info ---
$building_rules = $building_name = $moderator_mobile = $secrataty_mobile = $security_guard_mobile = '';
$row_apartment = null;
$result_apartment = mysqli_query($link, "SELECT * FROM tblbranch LIMIT 1");
if ($row_apartment = mysqli_fetch_array($result_apartment)) {
  $building_rules        = $row_apartment['building_rule'];
  $building_name         = $row_apartment['branch_name'];
  $moderator_mobile      = $row_apartment['moderator_mobile'];
  $secrataty_mobile      = $row_apartment['secrataty_mobile'];
  $security_guard_mobile = $row_apartment['security_guard_mobile'];
}

// --- Utils ---
function sanitize_number_for_wa($phone) {
  $clean = preg_replace('/\D+/', '', (string)$phone);
  if (substr($clean, 0, 3) !== '233') {
    $clean = '233' . ltrim($clean, '0');
  }
  return $clean;
}
function slug($s) {
  $s = preg_replace('~[^\pL\d]+~u', '-', $s);
  $s = @iconv('UTF-8', 'ASCII//TRANSLIT', $s);
  $s = preg_replace('~[^-\w]+~', '', $s);
  $s = trim($s, '-');
  $s = preg_replace('~-+~', '-', $s);
  return strtolower($s ?: 'file');
}
function normalize_currency_symbol($raw) {
  // 1) Decode entities: '&#8373;' -> '₵'
  $decoded = html_entity_decode((string)$raw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  $decoded = trim($decoded);

  // 2) Common variants -> normalize to single '₵'
  $candidate = mb_strtoupper($decoded, 'UTF-8');

  if ($candidate === 'GHS' || $candidate === 'GH₵' || $candidate === 'GH¢' || $candidate === '¢' || $candidate === 'GH CEDI' || $candidate === 'GH CEDIS' || $candidate === 'CEDI' || $candidate === 'CEDIS') {
    return "₵";
  }

  if ($decoded === "₵") {
    return "₵";
  }

  if ($decoded === '' || $decoded === '?' || $decoded === "�") {
    return "₵";
  }

  if (strpos($decoded, '¢') !== false) {
    return "₵";
  }

  return $decoded;
}

/* ---------------- Setup: shared CSS + HTML builder so screen = PDF = Print ---------------- */

$INVOICE_CSS = <<<CSS
  @page { margin: 28px; }
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --soft:#f8fafc; --soft2:#eef2ff; --brand:#2563eb;
    --ok:#10b981; --warn:#f59e0b; --danger:#ef4444;
  }
  * { box-sizing: border-box; }
  /* <<< IMPORTANT: Force DejaVu Sans which includes the Ghana cedi '₵' glyph */
  body { font-family: "DejaVu Sans", DejaVuSans, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; color:var(--ink); background:#f6f8fb; }

  .invoice-shell {
    max-width: 940px; margin: 26px auto; background:#fff; border:1px solid var(--line); border-radius:16px;
    box-shadow:0 16px 44px rgba(2,6,23,.08); overflow:hidden;
  }

  .inv-header {
    display:flex; align-items:center; justify-content:space-between; gap:16px;
    padding:22px 24px; background:linear-gradient(135deg,var(--soft),var(--soft2));
    border-bottom:1px solid var(--line);
  }
  .inv-brand { display:flex; align-items:center; gap:14px; }
  .inv-brand h2 { margin:0; font-weight:800; font-size:22px; letter-spacing:.2px; text-transform:uppercase; color:var(--ink); }
  .inv-sub { color:var(--muted); font-weight:800; text-transform:uppercase; letter-spacing:.45px; font-size:12px; }

  .inv-meta { text-align:right; color:var(--ink2); font-weight:700; }
  .badge { display:inline-block; padding:6px 12px; border-radius:999px; font-weight:900; font-size:12px; letter-spacing:.3px; }
  .badge-paid { background:var(--ok); color:#fff; }
  .badge-due  { background:var(--danger); color:#fff; }
  .badge-partial { background:var(--warn); color:#fff; }
  .status-note { margin-top:6px; font-size:12px; color:var(--ink2); }

  .inv-body { padding: 22px 24px; }
  .two-col { display:grid; grid-template-columns:1fr 1fr; gap:18px 28px; margin-bottom:12px; }
  .boxy { background:#fff; border:1px dashed var(--line); border-radius:12px; padding:14px 16px; }
  .label { color:var(--muted); text-transform:uppercase; letter-spacing:.35px; font-size:12px; font-weight:800; margin-bottom:6px; }
  .kv { line-height:1.5; }
  .kv .val { font-weight:900; color:var(--ink); }
  .kv .dim { color:var(--ink2); }

  .chips { display:flex; flex-wrap:wrap; gap:8px; margin-top:8px; }
  .chip { background:#f1f5f9; color:var(--ink2); border:1px solid var(--line); border-radius:999px; padding:6px 10px; font-size:12px; font-weight:700; }

  table.inv-table { width:100%; border-collapse:collapse; margin-top:18px; font-size:14px; }
  .inv-table th, .inv-table td { padding:12px 14px; border-bottom:1px solid var(--line); }
  .inv-table thead th { background:#eef2ff; color:var(--ink); font-weight:900; }
  .highlight { background:#fff7ed; color:#7c2d12; font-weight:900; }
  .inv-total td { font-weight:1000; border-top:2px solid var(--line); }

  .inv-footer { padding: 14px 24px 20px; text-align:center; color:var(--muted); border-top:1px dashed var(--line); background:#fbfdff; }

  @media print {
    body { background:#fff; }
    .action-bar, .content-header { display:none !important; }
    .invoice-shell { margin:0; border:none; box-shadow:none; }
    * {-webkit-print-color-adjust: exact; print-color-adjust: exact; }
  }
CSS;

function build_invoice_html($vars, $css, $wrap=true) {
  extract($vars);

  // Determine status for badge & note
  $epsilon = 0.005;
  $is_paid = ($grand_total >= 0 && abs($grand_total - $tenant_amt_paid) < $epsilon);
  $is_partial = (!$is_paid && $tenant_amt_paid > $epsilon);
  $pay_status = $is_paid ? 'PAID' : ($is_partial ? 'PARTIAL' : 'UNPAID');
  $badgeClass = ($pay_status === 'PAID') ? 'badge-paid' : (($pay_status === 'PARTIAL') ? 'badge-partial' : 'badge-due');
  $statusText = ($pay_status === 'PARTIAL') ? 'PARTIAL PAYMENT' : $pay_status;

  ob_start(); ?>
  <!doctype html>
  <html>
  <head>
    <meta charset="utf-8"><!-- <<< IMPORTANT -->
    <style><?= $css ?></style>
    <title><?= htmlspecialchars(($grand_total == $tenant_amt_paid) ? "RENT RECEIPT" : "RENT INVOICE") ?></title>
  </head>
  <body>
  <?php if ($wrap): ?><div class="invoice-shell" id="PrintRentInvoice"><?php endif; ?>

    <div class="inv-header">
      <div class="inv-brand">
        <div>
          <h2><?= htmlspecialchars($building_name ?: 'Property') ?></h2>
          <div class="inv-sub"><?= htmlspecialchars(($grand_total == $tenant_amt_paid) ? "RENT RECEIPT" : "RENT INVOICE") ?></div>
        </div>
      </div>
      <div class="inv-meta">
        <div style="margin-top:8px;"><span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($statusText) ?></span></div>
        <?php if ($pay_status === 'PARTIAL'): ?>
          <div class="status-note">
            Received <?= $currency_display . number_format($tenant_amt_paid, 2) ?> —
            Balance <?= $currency_display . number_format($balance, 2) ?> due.
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="inv-body">
      <div class="two-col">
        <div class="boxy">
          <div class="label">From</div>
          <div class="kv">
            <div class="val"><?= nl2br(htmlspecialchars($row_apartment['b_address'])) ?></div>
            <div class="dim">Phone: <strong><?= htmlspecialchars($row_apartment['b_contact_no']) ?></strong></div>
            <div class="dim">Email: <strong><?= htmlspecialchars($row_apartment['b_email']) ?></strong></div>
            <div class="chips">
              <span class="chip">Invoice #<?= htmlspecialchars($invoice_id) ?></span>
              <span class="chip"><?= htmlspecialchars($invoice_issue_date) ?></span>
            </div>
          </div>
        </div>
        <div class="boxy">
          <div class="label">Bill To</div>
          <div class="kv">
            <div class="val"><?= htmlspecialchars($tenant_name) ?></div>
            <div class="val"><?= htmlspecialchars($tenant_block) ?> - <?= htmlspecialchars($tenant_unit) ?></div>
            <div class="val"><?= htmlspecialchars($tenant_phone) ?></div>
            <div class="val"><?= htmlspecialchars($tenant_email) ?></div>
          </div>
        </div>
      </div>

      <table class="inv-table">
        <thead>
          <tr>
            <th>Description</th>
            <th style="text-align:right;">Amount</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td><?= htmlspecialchars($rate_label) ?></td>
            <td style="text-align:right;"><?= $currency_display . number_format($tenant_rent_bill, 2) ?></td>
          </tr>
          <tr>
            <td>Period (<?= htmlspecialchars($tenant_bill_period) ?>)</td>
            <td style="text-align:right;">
              <?= htmlspecialchars($period) ?>
              <?= ($period_type === "D" ? "Day" : ($period_type === "M" ? "Month" : "Year")) ?>
              <?= ($period > 1 ? "s" : "") ?>
            </td>
          </tr>
          <tr>
            <td>Amount Paid</td>
            <td style="text-align:right;"><?= $currency_display . number_format($tenant_amt_paid, 2) ?></td>
          </tr>
          <tr class="highlight">
            <td>Balance Due</td>
            <td style="text-align:right;"><?= $currency_display . number_format($balance, 2) ?></td>
          </tr>
          <tr class="inv-total">
             <td>Total</td>
            <td style="text-align:right;"><strong><?= $currency_display . number_format($total_bill, 2) ?></strong></td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="inv-footer">
      For more information, contact us on
      <a href="https://wa.me/233544106578" target="_blank" style="color:#0ea5e9;text-decoration:none;">+233 54 410 6578</a>
    </div>

  <?php if ($wrap): ?></div><?php endif; ?>
  </body>
  </html>
  <?php
  return ob_get_clean();
}

/* ------------ Resolve rentid (POST has priority to avoid stale GET) ------------ */
$rentid = null;
if (isset($_POST['rentid']) && (int)$_POST['rentid'] > 0) {
  $rentid = (int)$_POST['rentid'];
} elseif (isset($_GET['rentid']) && (int)$_GET['rentid'] > 0) {
  $rentid = (int)$_GET['rentid'];
} else {
  echo 'Wrong Request';
  die();
}

/* ------------ Fetch invoice data ------------ */
$invoice_id = $tenant_name = $tenant_phone = $tenant_email = $tenant_block = $tenant_unit = '';
$business_phone = '';
$tenant_bill_period = '';
$tenant_rent_bill = '0.00';
$tenant_service_fee = '';
$tenant_amt_paid = 0;
$period = 0;
$period_type = "";
$balance = 0;
$rate_currency = '';
$currency_display = '';
$grand_total = 0;
$total_bill = 0;
$invoice_issue_date = '';
$start_date = $end_date = '';
$rate_label = '';

$stmt = $link->prepare("SELECT * FROM rent_tenant_unit_view WHERE id = ?");
$stmt->bind_param("i", $rentid);
$stmt->execute();
$res = $stmt->get_result();
if ($row = $res->fetch_assoc()) {
  $invoice_id           = $row['id'];
  $invoice_issue_date   = date("M d, Y", strtotime($row['issue_date']));
  $tenant_name          = $row['r_name'];
  $tenant_phone         = $row['r_contact'];
  $tenant_email         = $row['r_email'];
  $business_phone       = $row['business_phone']; // WhatsApp destination
  $tenant_block         = $row['b_name'];
  $tenant_unit          = $row['unit_no'];
  $start_date           = date("jS F, Y", strtotime($row['start_date']));
  $end_date             = date("jS F, Y", strtotime($row['end_date']));
  $tenant_bill_period   = "$start_date - $end_date";
  $tenant_rent_bill     = (float)$row['rate'];
  $tenant_service_fee   = $row['m_rate'];
  $tenant_amt_paid      = (float)$row['amt_paid'];
  $period               = (int)$row['period'];
  $period_type          = $row['period_type'];
  $rate_currency        = $row['rate_currency'];     // may be '₵' or '&#8373;' or 'GH¢'
  $currency_display     = normalize_currency_symbol($rate_currency); // <<< IMPORTANT
  $grand_total          = (float)$row['total_rent'];
  $total_bill           = $grand_total;
  $balance              = $grand_total - $tenant_amt_paid;
} else {
  echo 'Wrong Request';
  die();
}
$stmt->close();

$rate_label = ($period_type === 'D') ? 'Rent per Day' : 'Rent per Month';
$cur_time = date("Y-m-d H:i:s");

/* ------------------------- Helpers to build & save PDF ------------------------- */
function generate_invoice_pdf($vars, $css) {
  $invoiceHtml = build_invoice_html($vars, $css, false);
  $dompdf = new Dompdf();

  // Unicode-friendly options
  $dompdf->set_option('defaultFont', 'DejaVu Sans');
  $dompdf->set_option('isFontSubsettingEnabled', true);
  $dompdf->set_option('isHtml5ParserEnabled', true);
  $dompdf->set_option('isRemoteEnabled', true);

  $dompdf->loadHtml($invoiceHtml, 'UTF-8');
  $dompdf->setPaper('A4', 'portrait');
  $dompdf->render();

  $pdfDir = ROOT_PATH . 'invoices/';
  if (!is_dir($pdfDir) && !mkdir($pdfDir, 0755, true)) {
    return [false, "ERROR: Failed to create invoices directory at $pdfDir", null, null];
  }

  $ts = date('Ymd_His');
  $fileBase = slug($vars['tenant_name']) . "-rent" . "-" . $ts;
  $pdfFilename = $fileBase . '.pdf';
  $pdfPath = $pdfDir . $pdfFilename;

  file_put_contents($pdfPath, $dompdf->output());
  if (!file_exists($pdfPath)) {
    return [false, "ERROR: PDF file was not created at $pdfPath", null, null];
  }

  // Public URL with cache-buster
  $pdfUrl =  'https://3b231ebcf920.ngrok-free.app/property/invoices/' . $pdfFilename . '?v=' . $ts. '?__ngrok_skip_browser_warning=true';
  return [true, "PDF generated successfully.", $pdfPath, $pdfUrl];
}

/* ------------------------- Handle WhatsApp send ------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_whatsapp'])) {
  $vars = compact(
    'building_name','row_apartment',
    'invoice_id','invoice_issue_date',
    'tenant_name','tenant_block','tenant_unit','tenant_phone','tenant_email',
    'rate_label','currency_display','tenant_rent_bill','tenant_bill_period','period','period_type',
    'tenant_amt_paid','balance','total_bill','grand_total'
  );

  list($ok, $msg, $pdfPath, $pdfUrl) = generate_invoice_pdf($vars, $INVOICE_CSS);
  if (!$ok) { die($msg); }

  // --- WhatsApp Cloud API send ---
  $waAccessToken   = 'EAAJxdEi83PUBO9obZBZBi6GWe2xSUYZBF7WhDzkNYgTzV2e4RCuKQL5hFOXwXTnTNgLaeaxXc9ywB7rse9qfxJsjLp9uIaqnNvaHVofNOMZAyfIBHEAXTpD7FArxsbZBLRRqXo4YExaSOQe9vZARgbCYVTvZAFnhQlW1yVZATbjVRrRJZCINEZC2ziTnifEmiZAMAZDZD';
  $waPhoneNumberId = '647902038411623';
  $waApiVersion    = 'v23.0';

  $recipient = sanitize_number_for_wa($business_phone);
  $pdfFilename = basename(parse_url($pdfUrl, PHP_URL_PATH));

  $waPayload = [
    'messaging_product' => 'whatsapp',
    'to'                => $recipient,
    'type'              => 'document',
    'document'          => [
      'link'     => $pdfUrl,
      'filename' => $pdfFilename
    ]
  ];

  $waEndpoint = "https://graph.facebook.com/{$waApiVersion}/{$waPhoneNumberId}/messages";
  $ch = curl_init($waEndpoint);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
      "Authorization: Bearer {$waAccessToken}",
      "Content-Type: application/json"
    ],
    CURLOPT_POSTFIELDS     => json_encode($waPayload, JSON_UNESCAPED_UNICODE)
  ]);
  $waResp = curl_exec($ch);
  $waErr  = curl_error($ch);
  curl_close($ch);

  if ($waErr) {
    $wa_status = 'failed';
  } else {
    $decoded = json_decode($waResp, true);
    if (isset($decoded['error'])) {
      $wa_status = 'failed';
    } elseif (isset($decoded['messages'][0]['id'])) {
      $wa_status = 'sent';
    } else {
      $wa_status = 'failed';
    }
  }

  $subjEsc  = mysqli_real_escape_string($link, "Invoice #$invoice_id");
  $msgEsc   = mysqli_real_escape_string($link, "Sent PDF: $pdfFilename");
  $nameEsc  = mysqli_real_escape_string($link, $tenant_name);
  $phoneEsc = mysqli_real_escape_string($link, $tenant_phone);

  $sqlLog = "
    INSERT INTO messages 
      (subject, message, channel, receiver, receiver_email, receiver_phone, status, time_created)
    VALUES 
      ('$subjEsc', '$msgEsc', 'whatsapp', '$nameEsc', '', '$phoneEsc', '$wa_status', '$cur_time')
  ";
  mysqli_query($link, $sqlLog);

  $notify = ($wa_status === 'sent') ? "WhatsApp invoice PDF sent successfully." : "WhatsApp send failed.";
}

/* ------------------------- NEW: Handle Generate PDF Link (no send) ------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_pdf'])) {
  $vars = compact(
    'building_name','row_apartment',
    'invoice_id','invoice_issue_date',
    'tenant_name','tenant_block','tenant_unit','tenant_phone','tenant_email',
    'rate_label','currency_display','tenant_rent_bill','tenant_bill_period','period','period_type',
    'tenant_amt_paid','balance','total_bill','grand_total'
  );

  list($ok, $msg, $pdfPath, $pdfUrl) = generate_invoice_pdf($vars, $INVOICE_CSS);
  if ($ok) {
    $notify = "PDF generated successfully. <a href=\"" . htmlspecialchars($pdfUrl) . "\" target=\"_blank\"><strong>Open/Download PDF</strong></a>";
    $notify_success = true;
  } else {
    $notify = htmlspecialchars($msg);
    $notify_success = false;
  }
}

/* ------------------------- Screen (same HTML as PDF) ------------------------- */
$varsForScreen = compact(
  'building_name','row_apartment',
  'invoice_id','invoice_issue_date',
  'tenant_name','tenant_block','tenant_unit','tenant_phone','tenant_email',
  'rate_label','currency_display','tenant_rent_bill','tenant_bill_period','period','period_type',
  'tenant_amt_paid','balance','total_bill','grand_total'
);
$invoiceHTML = build_invoice_html($varsForScreen, $INVOICE_CSS, true);
?>
<!-- Content Header (Page header) -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <?= ($grand_total == $tenant_amt_paid ? "Rent Receipt" : "Rent Invoice") ?>
  </h1>
</section>

<style>
  .action-bar {
    display:flex; gap:10px; justify-content:center; flex-wrap:wrap; margin:10px 0 14px;
  }
  .btn-pill { border-radius:999px !important; padding:9px 16px; font-weight:800; letter-spacing:.2px; }
  .btn-primary { background:#2563eb; border-color:#2563eb; }
  .btn-primary:hover { background:#1e40af; border-color:#1e40af; }
  .btn-success { background:#16a34a; border-color:#16a34a; }
  .btn-success:hover { background:#15803d; border-color:#15803d; }
  .btn-default { background:#111827; color:#fff; border-color:#111827; }
  .btn-default:hover { background:#0b1220; border-color:#0b1220; }
</style>

<!-- Main content -->
<section class="content">
  <?php if (isset($notify)) : ?>
    <div class="alert alert-<?= (isset($notify_success) ? ($notify_success ? 'success' : 'danger') : (($wa_status ?? '') === 'sent' ? 'success' : 'danger')) ?> alert-dismissable">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
      <?= $notify ?>
    </div>
  <?php endif; ?>

  <div class="action-bar">
    <a class="btn btn-primary btn-pill" onclick="printInvoiceExact();" href="javascript:void(0);">
      <i class="fa fa-print"></i> Print
    </a>

    <!-- NEW: Generate PDF Link button -->
    <form method="post" style="display:inline;">
      <input type="hidden" name="rentid" value="<?= (int)$invoice_id ?>">
      <button type="submit" name="generate_pdf" class="btn btn-default btn-pill" title="Generate a downloadable PDF link">
        <i class="fa fa-file-pdf-o"></i> Generate PDF Link
      </button>
    </form>

    <form method="post" style="display:inline;">
      <input type="hidden" name="rentid" value="<?= (int)$invoice_id ?>">
      <button type="submit" name="send_whatsapp" class="btn btn-success btn-pill" title="Send to business_phone via WhatsApp">
        <i class="fa fa-whatsapp"></i> Send PDF via WhatsApp
      </button>
    </form>
  </div>

  <?= $invoiceHTML ?>
</section>

<script>
function printInvoiceExact() {
  var html = document.getElementById('PrintRentInvoice').outerHTML;

  var win = window.open('', '', 'height=900,width=800');
  win.document.open();
  win.document.write(`<!doctype html>
  <html>
    <head>
      <meta charset="utf-8">
      <title><?= ($grand_total == $tenant_amt_paid ? "Rent Receipt" : "Rent Invoice") ?></title>
      <style><?= addslashes($INVOICE_CSS) ?></style>
    </head>
    <body>${html}</body>
  </html>`);
  win.document.close();
  win.focus();
  setTimeout(function(){ win.print(); }, 200);
}
</script>

<?php include_once('../footer.php'); ?>
