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

include_once('../header.php');
include_once('../utility/common.php');
include_once(ROOT_PATH.'language/'.$lang_code_global.'/lang_add_rented.php');

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  exit();
}

/* -------------------------------------------------
   Defaults
------------------------------------------------- */
$title             = $_data['add_new_renter'];
$button_text       = $_data['save_button_text'];
$successful_msg    = $_data['added_buyer_successfully'];
$form_url          = WEB_URL . "buyer/addbuyer.php";
$image_rnt         = WEB_URL . 'img/no_image.jpg';
$img_track         = '';
$attachment_url    = '';
$document_name     = '';

$buyer_name        = '';
$buyer_email       = '';
$buyer_contact     = '';
$buyer_address     = '';
$r_status          = '1';
$business_name     = '';
$business_phone    = '';
$nature_of_business= "";

/* -------------------------------------------------
   POST: Create / Update / Assign
------------------------------------------------- */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $data = post_input_serilization();
  $id   = isset($_GET["id"]) ? (int)$_GET["id"] : 0;

  // Server-side guard: Only name & contact are mandatory
  $nameRequired    = trim($data['txtRName'] ?? '');
  $contactRequired = trim($data['txtRContact'] ?? '');
  if ($nameRequired === '' || $contactRequired === '') {
    $_SESSION["message"] = "Name and Contact are required.";
    header("Location: " . WEB_URL . "buyer/addbuyer.php");
    exit();
  }

  /* UPDATE EXISTING BUYER */
  if ($id > 0) {
    $image_url = uploadImage();
    if ($image_url === '') $image_url = $data['img_exist'] ?? '';

    // Make all optional fields safe strings
    $buyer_email_opt        = $data['txtREmail'] ?? '';
    $buyer_address_opt      = $data['txtRAddress'] ?? '';
    $business_name_opt      = $data['business_name'] ?? '';
    $business_phone_opt     = $data['business_phone'] ?? '';
    $nature_of_business_opt = $data['nature_of_business'] ?? '';

    $stmt = $link->prepare("
      UPDATE `buyers` SET
        `buyer_name`=?,
        `buyer_email`=?,
        `buyer_contact`=?,
        `business_name`=?,
        `business_phone`=?,
        `nature_of_business`=?,
        `image`=?,
        `buyer_address`=?
      WHERE bbid = ?
    ");
    $stmt->bind_param(
      'ssssssssi',
      $nameRequired,
      $buyer_email_opt,
      $contactRequired,
      $business_name_opt,
      $business_phone_opt,
      $nature_of_business_opt,
      $image_url,
      $buyer_address_opt,
      $id
    );
    $ok = $stmt->execute();
    $stmt->close();

    $_SESSION["message"] = $ok ? "Buyer Information Updated Successfully" : "Failed to Update Buyer Information";
    header("Location: " . WEB_URL . "buyer/buyerlist.php?m=up");
    exit();
  }

  /* ASSIGN TENANT -> UNIT */
  if (isset($_GET["action"]) && $_GET["action"] === "assign") {
    $uid = (int)($_POST["uid"] ?? 0);
    $tid = (int)($_POST["tid"] ?? 0);

    $stmt = $link->prepare("INSERT INTO tenant_unit (`uid`, `tid`, `last_action_by`) VALUES (?, ?, ?)");
    $stmt->bind_param('iii', $uid, $tid, $_SESSION["user_id"]);
    $stmt->execute();
    $stmt->close();

    header("Location: " . WEB_URL . "tenant/tenantlist.php?m=assign");
    exit();
  }

  /* CREATE NEW BUYER */
  $attachment   = uploadPDF();   // optional
  $image_url    = uploadImage(); // optional

  // Optional fields fallback
  $buyer_email_opt        = $data['txtREmail'] ?? '';
  $buyer_address_opt      = $data['txtRAddress'] ?? '';
  $business_name_opt      = $data['business_name'] ?? '';
  $business_phone_opt     = $data['business_phone'] ?? '';
  $nature_of_business_opt = $data['nature_of_business'] ?? '';
  $document_name_opt      = $data['document_name'] ?? '';

  $stmt = $link->prepare("
    INSERT INTO buyers
      (buyer_name, buyer_email, buyer_contact, buyer_address,
       business_name, business_phone, nature_of_business,
       image, document_name, attachments)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  ");
  $stmt->bind_param(
    'ssssssssss',
    $nameRequired,
    $buyer_email_opt,
    $contactRequired,
    $buyer_address_opt,
    $business_name_opt,
    $business_phone_opt,
    $nature_of_business_opt,
    $image_url,
    $document_name_opt,
    $attachment
  );
  $stmt->execute();
  $stmt->close();

  header("Location: " . WEB_URL . 'buyer/buyerlist.php?m=add');
  exit();
}

/* -------------------------------------------------
   GET: Edit prefill
------------------------------------------------- */
if (isset($_GET['id']) && $_GET['id'] !== '') {
  $res = $link->query("SELECT * FROM buyers WHERE bbid = " . (int)$_GET['id'] . " LIMIT 1");
  if ($row = $res->fetch_assoc()) {
    $buyer_name         = $row['buyer_name'];
    $buyer_email        = $row['buyer_email'];
    $buyer_contact      = $row['buyer_contact'];
    $buyer_address      = $row['buyer_address'];
    $business_name      = $row['business_name'];
    $business_phone     = $row['business_phone'];
    $nature_of_business = $row["nature_of_business"];
    $r_status           = $row['r_status'] ?? '1';
    $document_name      = $row['document_name'] ?? '';
    $attachment_url     = $row['attachments'] ?? '';

    if (!empty($row['image'])) {
      $image_rnt = WEB_URL . 'img/upload/' . $row['image'];
      $img_track = $row['image'];
    }
    $title          = $_data['update_buyer'];
    $button_text    = $_data['update_button_text'];
    $successful_msg = $_data['update_buyer_successfully'];
    $form_url       = WEB_URL . "buyer/addbuyer.php?id=" . (int)$_GET['id'];
  }
  mysqli_close($link);
}

/* -------------------------------------------------
   Helpers: Uploads + GUID
------------------------------------------------- */
function uploadImage() {
  if (!empty($_FILES["uploaded_file"]) && $_FILES['uploaded_file']['error'] === 0) {
    $filename = basename($_FILES['uploaded_file']['name']);
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $okTypes = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'];
    $mime = $_FILES["uploaded_file"]["type"];

    if (isset($okTypes[$ext]) && stripos($mime, explode('/', $okTypes[$ext])[1]) !== false) {
      $newfilename = NewGuid() . '.' . $ext;
      move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], ROOT_PATH . '/img/upload/' . $newfilename);
      return $newfilename;
    }
  }
  return '';
}

function uploadPDF() {
  if (!empty($_FILES["pdf_attachment"]) && $_FILES['pdf_attachment']['error'] === 0) {
    $filename = basename($_FILES['pdf_attachment']['name']);
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if ($ext === "pdf") {
      $newfilename = NewGuid() . '.' . $ext;
      move_uploaded_file($_FILES["pdf_attachment"]["tmp_name"], ROOT_PATH . '/attachments/' . $newfilename);
      return WEB_URL . 'attachments/' . $newfilename;
    }
  }
  return '';
}

function NewGuid() {
  $s = strtoupper(md5(uniqid(rand(), true)));
  return substr($s,0,8) . '-' . substr($s,8,4) . '-' . substr($s,12,4) . '-' . substr($s,16,4) . '-' . substr($s,20);
}
?>
<!-- Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <span style="display:inline-flex;width:38px;height:38px;border-radius:12px;background:#2563eb15;align-items:center;justify-content:center;">
      <i class="fa fa-user-plus" style="color:#1e40af;"></i>
    </span>
    <span><?= htmlspecialchars($title); ?></span>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL?>dashboard.php"><i class="fa fa-dashboard"></i> <?= $_data['home_breadcam'];?></a></li>
    <li class="active"><?= $_data['add_new_buyer_information_breadcam'];?></li>
    <li class="active"><?= htmlspecialchars($title); ?></li>
  </ol>
</section>

<!-- Fonts & Style -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --brand:#2563eb; --brand-2:#1e40af; --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
    --soft:#f8fafc; --soft2:#eef2ff; --card:#ffffff; --shadow:0 14px 40px rgba(2,6,23,.08);
  }
  .content-wrapper, .box, label, .btn, input, select, textarea, body {
    font-family: 'Inter', system-ui, Segoe UI, Roboto, Helvetica, Arial;
    color: var(--ink2);
  }

  .box.box-success{
    border:1px solid var(--line);
    border-radius:18px; overflow:hidden; background:var(--card); box-shadow:var(--shadow);
  }
  .box .box-header{
    background:linear-gradient(135deg,var(--soft),var(--soft2));
    border-bottom:1px solid var(--line); padding:14px 16px;
  }
  .box .box-title{ margin:0; font-weight:800; color:var(--ink); letter-spacing:.2px; }

  .form-grid { display:grid; grid-template-columns: 1.3fr .7fr; gap:16px; align-items:start; }
  @media (max-width: 1100px){ .form-grid{ grid-template-columns:1fr; } }

  .card { border:1px solid var(--line); border-radius:16px; background:#fff; padding:16px; }
  .section-title { display:flex; gap:8px; align-items:center; margin:0 0 12px; font-weight:800; color:var(--ink); }
  .section-title i { color:var(--brand-2); }

  .form-control { height:44px; border-radius:12px; border:1px solid var(--line); box-shadow:none !important; }
  textarea.form-control { height:auto; min-height:100px; resize:vertical; }
  .form-control:focus { border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.15); }

  .input-with-icon { position:relative; }
  .input-with-icon i {
    position:absolute; left:12px; top:50%; transform:translateY(-50%); color:#94a3b8;
  }
  .input-with-icon input { padding-left:36px; }
  .input-with-icon textarea { padding-left:36px; }

  .btn { border-radius:12px; font-weight:700; padding:.55rem .9rem; }
  .btn-success { background:var(--ok); border-color:var(--ok); }
  .btn-warning { background:#f59e0b; border-color:#f59e0b; }
  .btn-primary { background:var(--brand); border-color:var(--brand); }
  .btn-default { background:#e5e7eb; border-color:#e5e7eb; color:#111827; }
  .btn:hover { filter:brightness(.98); }

  .pill {
    display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:999px;
    background:#f3f4f6; color:#111827; font-size:12px; font-weight:700; border:1px solid var(--line);
  }
  .preview {
    display:flex; gap:12px; align-items:center; margin-top:6px;
  }
  .preview img {
    width:96px; height:96px; border-radius:12px; object-fit:cover; border:1px solid var(--line);
  }
  .file-row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
  .file-chip { border:1px dashed var(--line); border-radius:12px; padding:8px 10px; font-size:12px; color:var(--muted); display:flex; gap:8px; align-items:center; }
  .help-note { font-size:12px; color:var(--muted); margin-top:6px; }
  .optional { color:#64748b; font-weight:600; margin-left:6px; font-size:12px; }
</style>

<!-- Main content -->
<section class="content">
  <div class="box box-success">
    <div class="box-header">
      <h3 class="box-title"><i class="fa fa-id-card-o"></i> <?= $_data['add_new_buyer_entry_form'];?></h3>
    </div>

    <form onsubmit="return validateMe();" action="<?= htmlspecialchars($form_url); ?>" method="post" enctype="multipart/form-data" id="frm_renter_entry">
      <div class="box-body">
        <div class="form-grid">
          <!-- LEFT: Form fields -->
          <div class="card">
            <h4 class="section-title"><i class="fa fa-user-circle"></i> Buyer Details</h4>

            <div class="row">
              <div class="form-group col-md-6 input-with-icon">
                <label for="txtRName"><span style="color:#dc2626">*</span> <?= $_data['add_new_form_field_1_text'];?></label>
                <i class="fa fa-user"></i>
                <input type="text" name="txtRName" value="<?= htmlspecialchars($buyer_name);?>" required id="txtRName" class="form-control" placeholder="Full name" />
              </div>

              <div class="form-group col-md-6 input-with-icon">
                <label for="txtREmail"><?= $_data['add_new_form_field_text_2'];?> <span class="optional">(optional)</span></label>
                <i class="fa fa-envelope"></i>
                <input type="email" name="txtREmail" value="<?= htmlspecialchars($buyer_email);?>" id="txtREmail" class="form-control" placeholder="name@example.com" />
              </div>
            </div>

            <div class="row">
              <div class="form-group col-md-6">
                <label for="txtRContact"><span style="color:#dc2626">*</span> <?= $_data['add_new_form_field_text_4'];?></label>
                <input type="tel" value="<?= htmlspecialchars($buyer_contact);?>" required id="txtRContact" class="form-control phone w-100" placeholder="Buyer phone" />
                <input type="hidden" name="txtRContact" value="" required id="contact_hidden" />
                <div class="help-note">Use international format (e.g., +233...).</div>
              </div>

              <div class="form-group col-md-6 input-with-icon">
                <label for="business_phone">Business Phone <span class="optional">(optional)</span></label>
                <i class="fa fa-phone"></i>
                <input type="text" value="<?= htmlspecialchars($business_phone); ?>" id="business_phone" class="form-control phone w-100" placeholder="Business phone" />
                <input type="hidden" name="business_phone" value="" id="business_phone_hidden" />
              </div>
            </div>

            <div class="row">
              <div class="form-group col-md-6 input-with-icon">
                <label for="business_name">Business Name <span class="optional">(optional)</span></label>
                <i class="fa fa-building"></i>
                <input type="text" name="business_name" value="<?= htmlspecialchars($business_name); ?>" id="business_name" class="form-control" placeholder="Registered business name" />
              </div>

              <div class="form-group col-md-6 input-with-icon">
                <label for="nature_of_business">Nature of Business <span class="optional">(optional)</span></label>
                <i class="fa fa-briefcase"></i>
                <input type="text" name="nature_of_business" value="<?= htmlspecialchars($nature_of_business); ?>" id="nature_of_business" class="form-control" placeholder="E.g., Retail, Manufacturing" />
              </div>
            </div>

            <div class="form-group input-with-icon">
              <label for="txtRAddress"><?= $_data['add_new_form_field_text_5'];?> <span class="optional">(optional)</span></label>
              <i class="fa fa-map-marker"></i>
              <textarea name="txtRAddress" id="txtRAddress" class="form-control" placeholder="Street, City, Region"><?= htmlspecialchars($buyer_address);?></textarea>
            </div>

            <hr>

            <h4 class="section-title"><i class="fa fa-file-pdf-o"></i> Supporting Document</h4>
            <div class="row">
              <div class="form-group col-md-6 input-with-icon">
                <label for="document_name">Name of Document <span class="optional">(optional)</span></label>
                <i class="fa fa-tag"></i>
                <input type="text" name="document_name" value="<?= htmlspecialchars($document_name); ?>" id="document_name" class="form-control" placeholder="E.g., Business Registration Certificate" />
              </div>

              <div class="form-group col-md-6">
                <label>PDF Attachment <span class="optional">(optional)</span></label>
                <div class="file-row">
                  <input type="file" name="pdf_attachment" id="pdf_attachment" accept="application/pdf" class="form-control" style="display:none;" />
                  <button type="button" class="btn btn-primary" onclick="document.getElementById('pdf_attachment').click();">
                    <i class="fa fa-paperclip"></i> Choose PDF
                  </button>
                  <span id="pdf_name" class="file-chip" aria-live="polite">
                    <i class="fa fa-info-circle"></i> No file chosen
                  </span>
                  <?php if (!empty($attachment_url)): ?>
                    <a class="btn btn-default" href="<?= htmlspecialchars($attachment_url) ?>" target="_blank">
                      <i class="fa fa-external-link"></i> View Current
                    </a>
                  <?php endif; ?>
                </div>
                <div class="help-note">Attach a single PDF (optional).</div>
              </div>
            </div>

            <hr>

            <h4 class="section-title"><i class="fa fa-picture-o"></i> Photo</h4>
            <div class="row">
              <div class="form-group col-md-6">
                <label><?= $_data['add_new_form_field_text_15'];?> <span class="optional">(optional)</span></label>
                <div class="preview">
                  <img class="form-control" src="<?= htmlspecialchars($image_rnt); ?>" id="output" alt="Buyer image preview" />
                  <div>
                    <span class="btn btn-default btn-file">
                      <i class="fa fa-upload"></i> <?= $_data['upload_image'];?>
                      <input type="file" name="uploaded_file" accept="image/*" onchange="loadFile(event)" />
                    </span>
                    <div class="help-note">JPEG/PNG/GIF supported (optional).</div>
                  </div>
                </div>
                <input type="hidden" name="img_exist" value="<?= htmlspecialchars($img_track); ?>" />
              </div>
            </div>

          </div>

          <!-- RIGHT: Summary -->
          <aside class="card">
            <h4 class="section-title"><i class="fa fa-info-circle"></i> Summary</h4>

            <div style="display:grid; gap:10px;">
              <div class="pill"><i class="fa fa-user"></i> <span id="s_name"><?= htmlspecialchars($buyer_name ?: 'Name: —');?></span></div>
              <div class="pill"><i class="fa fa-envelope"></i> <span id="s_email"><?= htmlspecialchars($buyer_email ?: 'Email: —');?></span></div>
              <div class="pill"><i class="fa fa-phone"></i> <span id="s_phone"><?= $buyer_contact ? htmlspecialchars($buyer_contact) : 'Phone: —';?></span></div>
              <div class="pill"><i class="fa fa-building"></i> <span id="s_biz"><?= $business_name ? htmlspecialchars($business_name) : 'Business: —';?></span></div>
              <div class="pill"><i class="fa fa-briefcase"></i> <span id="s_nature"><?= $nature_of_business ? htmlspecialchars($nature_of_business) : 'Nature: —';?></span></div>
              <div class="pill"><i class="fa fa-map-marker"></i> <span id="s_addr"><?= $buyer_address ? htmlspecialchars($buyer_address) : 'Address: —';?></span></div>
              <div class="pill"><i class="fa fa-file-text-o"></i> <span id="s_doc"><?= $document_name ? htmlspecialchars($document_name) : 'Document: —';?></span></div>
              <div class="pill"><i class="fa fa-paperclip"></i> <span id="s_pdf"><?= $attachment_url ? 'PDF: Attached' : 'PDF: —';?></span></div>
            </div>

            <div class="help-note" style="margin-top:10px;">This updates as you type.</div>
          </aside>
        </div>
      </div>

      <!-- Footer actions -->
      <div class="box-footer" style="display:flex; justify-content:flex-end; gap:10px;">
        <button type="submit" name="button" class="btn btn-success">
          <i class="fa fa-floppy-o"></i> <?= htmlspecialchars($button_text); ?>
        </button>
        <a class="btn btn-warning" href="<?= WEB_URL; ?>tenant/tenantlist.php">
          <i class="fa fa-reply"></i> <?= $_data['back_text'];?>
        </a>
      </div>
    </form>
  </div>
</section>

<!-- Behavior -->
<script>
  // Image preview
  function loadFile(event){
    const out = document.getElementById('output');
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      const url = URL.createObjectURL(file);
      out.src = url;
    }
  }

  // PDF filename display
  const pdfInput = document.getElementById('pdf_attachment');
  const pdfName  = document.getElementById('pdf_name');
  if (pdfInput) {
    pdfInput.addEventListener('change', function(){
      if (this.files && this.files.length > 0) {
        pdfName.innerHTML = '<i class="fa fa-file-pdf-o"></i> ' + this.files[0].name;
      } else {
        pdfName.innerHTML = '<i class="fa fa-info-circle"></i> No file chosen';
      }
      const s_pdf = document.getElementById('s_pdf');
      if (s_pdf) s_pdf.textContent = (this.files && this.files.length > 0) ? 'PDF: Attached' : 'PDF: —';
    });
  }

  // IntlTelInput submit handler: ONLY contact is mandatory (business phone optional)
  function validateMe(){
    try{
      if (window.intlTelInputGlobals && window.intlTelInputGlobals.getInstance) {
        let iti = window.intlTelInputGlobals.getInstance(document.getElementById("txtRContact"));
        document.getElementById("contact_hidden").value = iti ? iti.getNumber() : document.getElementById("txtRContact").value;

        iti = window.intlTelInputGlobals.getInstance(document.getElementById("business_phone"));
        document.getElementById("business_phone_hidden").value = iti ? iti.getNumber() : document.getElementById("business_phone").value;
      } else {
        document.getElementById("contact_hidden").value = document.getElementById("txtRContact").value;
        document.getElementById("business_phone_hidden").value = document.getElementById("business_phone").value;
      }

      // Basic guard for required fields (name + contact)
      if (!document.getElementById("txtRName").value.trim()) { alert("Name is required."); return false; }
      if (!document.getElementById("contact_hidden").value.trim()) { alert("Contact is required."); return false; }

      return true;
    } catch (exp){
      console.log(exp);
      alert("Error submitting form. Please try again.");
      return false;
    }
  }

  // Live summary updates
  function txt(id){ const el = document.getElementById(id); return el ? el.value : ''; }
  function setSpan(id, val){ const el = document.getElementById(id); if (el) el.textContent = val; }

  function updateSummary(){
    setSpan('s_name',  txt('txtRName')           ? txt('txtRName')           : 'Name: —');
    setSpan('s_email', txt('txtREmail')          ? txt('txtREmail')          : 'Email: —');
    setSpan('s_biz',   txt('business_name')      ? txt('business_name')      : 'Business: —');
    setSpan('s_nature',txt('nature_of_business') ? txt('nature_of_business') : 'Nature: —');
    setSpan('s_addr',  txt('txtRAddress')        ? txt('txtRAddress')        : 'Address: —');
    setSpan('s_doc',   txt('document_name')      ? txt('document_name')      : 'Document: —');
    setSpan('s_phone', document.getElementById('txtRContact').value ? document.getElementById('txtRContact').value : 'Phone: —');
  }

  ['txtRName','txtREmail','txtRContact','business_name','business_phone','nature_of_business','txtRAddress','document_name'].forEach(function(id){
    const el = document.getElementById(id);
    if (el) el.addEventListener('input', updateSummary);
  });
  document.addEventListener('DOMContentLoaded', updateSummary);

  // Prefill numbers with intlTelInput if values exist
  <?php if ($buyer_contact != ""): ?>
  (function(){ try{
      let el = document.getElementById("txtRContact");
      if (window.intlTelInputGlobals && el) {
        let iti = window.intlTelInputGlobals.getInstance(el);
        if (iti) iti.setNumber("<?= htmlspecialchars($buyer_contact, ENT_QUOTES); ?>");
      } else { el.value = "<?= htmlspecialchars($buyer_contact, ENT_QUOTES); ?>"; }
    }catch(_){}})();
  <?php endif; ?>

  <?php if ($business_phone != ""): ?>
  (function(){ try{
      let el = document.getElementById("business_phone");
      if (window.intlTelInputGlobals && el) {
        let iti = window.intlTelInputGlobals.getInstance(el);
        if (iti) iti.setNumber("<?= htmlspecialchars($business_phone, ENT_QUOTES); ?>");
      } else { el.value = "<?= htmlspecialchars($business_phone, ENT_QUOTES); ?>"; }
    }catch(_){}})();
  <?php endif; ?>
</script>

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