<?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");
  die();
}

/* ------------------------------- Helpers ------------------------------- */
function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function _val($arr, $key){ return isset($arr[$key]) ? trim($arr[$key]) : ''; }

/* ------------------------------- Defaults ------------------------------- */
$r_name              = '';
$r_email             = '';
$r_contact           = '';
$r_address           = '';
$r_status            = '1';
$business_name       = '';
$business_phone      = '';
$nature_of_business  = "";
$document_name       = '';
$existing_attachment = '';
$image_rnt           = WEB_URL . 'img/no_image.jpg';
$img_track           = '';

$title          = $_data['add_new_renter'];
$button_text    = $_data['save_button_text'];
$successful_msg = $_data['added_renter_successfully'];
$form_url       = WEB_URL . "tenant/addtenant.php";

/* ------------------------------- Upload helpers ------------------------------- */
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);
}

function uploadImage(){
  if(!empty($_FILES["uploaded_file"]) && $_FILES['uploaded_file']['error'] == 0){
    $filename = basename($_FILES['uploaded_file']['name']);
    $ext  = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $mime = $_FILES["uploaded_file"]["type"];
    $ok   = ($ext === "jpg"  && $mime === 'image/jpeg') ||
            ($ext === "jpeg" && $mime === 'image/jpeg') ||
            ($ext === "png"  && $mime === 'image/png')  ||
            ($ext === "gif"  && $mime === 'image/gif');
    if($ok){
      $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 '';
}

/* ------------------------------- Handle POST ------------------------------- */
if($_SERVER["REQUEST_METHOD"] === "POST"){
  $data = post_input_serilization();
  $id   = (int)($data["id"] ?? 0);

  $txtRName             = _val($data, 'txtRName');
  $txtREmail            = _val($data, 'txtREmail');
  $txtRContact          = _val($data, 'txtRContact');            // comes from hidden field
  $txtRAddress          = _val($data, 'txtRAddress');
  $business_name_p      = _val($data, 'business_name');
  $business_phone_p     = _val($data, 'business_phone');        // comes from hidden field
  $nature_of_business_p = _val($data, 'nature_of_business');
  $document_name_p      = _val($data, 'document_name');

  // UPDATE existing tenant
  if(isset($_GET["id"]) && $_GET["id"] !== ""){
    $image_url = uploadImage();
    if($image_url == ''){ $image_url = _val($data, 'img_exist'); }

    $sql = "
      UPDATE tenants
      SET r_name = '".$txtRName."',
          r_email = '".$txtREmail."',
          r_contact = '".$txtRContact."',
          business_name = '".$business_name_p."',
          business_phone = '".$business_phone_p."',
          nature_of_business = '".$nature_of_business_p."',
          image = '".$image_url."',
          r_address = '".$txtRAddress."',
          document_name = '".$document_name_p."'
      WHERE tid = ".(int)$_GET['id'];

    if($link->query($sql)){
      $_SESSION["message"] = "Tenant information updated successfully.";
    } else {
      $_SESSION["message"] = "Failed to update tenant information.";
    }

  // ASSIGN tenant to unit
  } else if(isset($_GET["action"]) && $_GET["action"] === "assign"){
    $uid = $data["uid"] ?? '';
    $tid = $data["tid"] ?? '';
    $sql = "INSERT INTO tenant_unit(`uid`, `tid`, `last_action_by`) VALUES('".$uid."', '".$tid."', '".$_SESSION["user_id"]."')";
    mysqli_query($link, $sql);

  // CREATE new tenant
  } else {
    $attachment = uploadPDF();
    $image_url  = uploadImage();
    $sql = "
      INSERT INTO tenants
        (r_name, r_email, r_contact, r_address, business_name, business_phone, nature_of_business, image, document_name, attachments)
      VALUES
        ('".$txtRName."','".$txtREmail."','".$txtRContact."','".$txtRAddress."',
         '".$business_name_p."','".$business_phone_p."','".$nature_of_business_p."',
         '".$image_url."','".$document_name_p."','".$attachment."')";
    $link->query($sql);
    mysqli_close($link);
  }

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

/* ------------------------------- Edit Mode ------------------------------- */
else if(isset($_GET['id']) && $_GET['id'] != ''){
  $result = mysqli_query($link,"SELECT * FROM tenants WHERE tid = '".(int)$_GET['id']."'");
  if($row = mysqli_fetch_array($result)){
    $r_name              = $row['r_name'];
    $r_email             = $row['r_email'];
    $r_contact           = $row['r_contact'];
    $r_address           = $row['r_address'];
    $business_name       = $row['business_name'];
    $business_phone      = $row['business_phone'];
    $nature_of_business  = $row['nature_of_business'];
    $r_status            = $row['r_status'];
    $document_name       = $row['document_name'];
    $existing_attachment = $row['attachments'];

    if($row['image'] != ''){
      $image_rnt = WEB_URL . 'img/upload/' . $row['image'];
      $img_track = $row['image'];
    }

    $title          = $_data['update_rent'];
    $button_text    = $_data['update_button_text'];
    $successful_msg = $_data['update_renter_successfully'];
    $form_url       = WEB_URL . "tenant/addtenant.php?id=".(int)$_GET['id'];
  }
  mysqli_close($link);
}
?>

<!-- Prefill intl-tel-input values on edit (runs after plugin loads) -->
<?php if($r_contact != ""){ ?>
<script>
  $(function(){
    try{
      var inst = window.intlTelInputGlobals.getInstance($("#txtRContact")[0]);
      if(inst) inst.setNumber("<?= h($r_contact) ?>");
      else $("#txtRContact").val("<?= h($r_contact) ?>");
    }catch(e){}
  });
</script>
<?php } ?>
<?php if($business_phone != ""){ ?>
<script>
  $(function(){
    try{
      var inst2 = window.intlTelInputGlobals.getInstance($("#business_phone")[0]);
      if(inst2) inst2.setNumber("<?= h($business_phone) ?>");
      else $("#business_phone").val("<?= h($business_phone) ?>");
    }catch(e){}
  });
</script>
<?php } ?>

<!-- ============== Header ============== -->
<section class="content-header" style="margin-bottom:8px;">
  <h1 style="display:flex;align-items:center;gap:12px;margin:0 0 6px;">
    <span style="display:inline-flex;width:44px;height:44px;border-radius:12px;background:#2563eb1a;align-items:center;justify-content:center;">
      <i class="fa fa-user" style="color:#1e40af;"></i>
    </span>
    <span style="font-weight:800;letter-spacing:.2px;"><?= h($title);?></span>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL?>dashboard.php"><i class="fa fa-dashboard"></i> <?= h($_data['home_breadcam']);?></a></li>
    <li class="active"><?= h($_data['add_new_renter_information_breadcam']);?></li>
    <li class="active"><?= h($title);?></li>
  </ol>
</section>

<!-- ============== Styles ============== -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e2e8f0;
    --soft:#f8fafc; --soft2:#eef2ff; --brand:#2563eb; --brand2:#1e40af;
    --ok:#16a34a; --warn:#f59e0b; --danger:#ef4444; --card:#fff;
  }
  .content-wrapper, .box, .table, label, input, select, textarea, .btn {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial; color:var(--ink2);
  }

  /* Card */
  .box.box-success{
    border:1px solid var(--line); border-radius:18px; overflow:hidden; background:var(--card);
    box-shadow:0 18px 44px rgba(2,6,23,.07);
  }
  .box .box-header{
    display:flex; align-items:center; justify-content:space-between; gap:12px;
    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 controls */
  .form-group label{ font-weight:700; color:#111827; }
  .form-control{ height:42px; border:1px solid var(--line); border-radius:12px; box-shadow:none !important; }
  .form-control:focus{ border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.15); }
  textarea.form-control{ min-height:96px; padding-top:10px; }

  .input-group-addon{
    background:#fff; border:1px solid var(--line); border-right:none; color:#6b7280;
    border-radius:12px 0 0 12px; min-width:44px; text-align:center;
  }
  .with-icon .form-control{ border-left:0; border-radius:0 12px 12px 0; }

  /* Media / file zones */
  .media-row{ display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
  .avatar{
    width:110px; height:110px; border-radius:16px; object-fit:cover; border:1px dashed var(--line); background:#fff;
    box-shadow:0 8px 22px rgba(2,6,23,.06);
  }
  .file-zone{
    border:1px dashed var(--line); border-radius:14px; padding:12px; background:#fff; display:flex; align-items:center; gap:10px; flex-wrap:wrap;
  }
  .file-note{ font-size:12px; color:var(--muted); }

  /* Buttons */
  .btn{ border-radius:10px; font-weight:700; }
  .btn-success{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-success:hover{ background:#15803d; border-color:#15803d; }
  .btn-warning{ background:var(--warn); border-color:var(--warn); color:#111827; }
  .btn-warning:hover{ background:#d97706; border-color:#d97706; }
  .btn-default{ background:#f3f4f6; border-color:#e5e7eb; color:#111827; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-primary:hover{ background:#1d4ed8; border-color:#1d4ed8; }

  .help{ font-size:12px; color:var(--muted); margin-top:6px; }
  .errorStar{ color:var(--danger); }

  /* Grid polish */
  @media (min-width: 992px){
    .col-md-6+.col-md-6 { padding-left:8px; }
    .col-md-6 { padding-right:8px; }
  }
</style>

<!-- ============== Main ============== -->
<section class="content">
  <div class="row">
    <div class="col-md-12">
      <div class="box box-success">
        <div class="box-header">
          <h3 class="box-title"><i class="fa fa-id-card-o"></i> <?= h($_data['add_new_renter_entry_form']);?></h3>
          <div class="help"><?= h($successful_msg); ?></div>
        </div>

        <form id="frm_renter_entry" action="<?= h($form_url); ?>" method="post" enctype="multipart/form-data" onsubmit="return validateMe();">
          <div class="box-body row" style="padding:18px;">

            <!-- Name -->
            <div class="form-group col-md-6">
              <label for="txtRName"><span class="errorStar">*</span> <?= h($_data['add_new_form_field_text_1']);?> :</label>
              <div class="input-group with-icon">
                <span class="input-group-addon"><i class="fa fa-user"></i></span>
                <input type="text" name="txtRName" id="txtRName" value="<?= h($r_name);?>" required class="form-control" placeholder="Full name">
              </div>
              <div class="help">Enter the tenant’s legal name.</div>
            </div>

            <!-- Email -->
            <div class="form-group col-md-6">
              <label for="txtREmail"><?= h($_data['add_new_form_field_text_2']);?> :</label>
              <div class="input-group with-icon">
                <span class="input-group-addon"><i class="fa fa-envelope-o"></i></span>
                <input type="email" name="txtREmail" id="txtREmail" value="<?= h($r_email);?>" class="form-control" placeholder="tenant@email.com">
              </div>
              <div class="help">Optional but helpful for sending notices.</div>
            </div>

            <!-- Phone -->
            <div class="form-group col-md-6">
              <label for="txtRContact"><span class="errorStar">*</span> <?= h($_data['add_new_form_field_text_4']);?> :</label>
              <div class="input-group with-icon">
                <span class="input-group-addon"><i class="fa fa-phone"></i></span>
                <input type="tel" id="txtRContact" value="<?= h($r_contact);?>" class="form-control phone" placeholder="Primary phone (international format)">
              </div>
              <input type="hidden" name="txtRContact" id="contact_hidden" value="">
              <div class="help">We’ll store the fully formatted international number.</div>
            </div>

            <!-- Address -->
            <div class="form-group col-md-6">
              <label for="txtRAddress"><?= h($_data['add_new_form_field_text_5']);?> :</label>
              <textarea name="txtRAddress" id="txtRAddress" class="form-control" placeholder="Street, City, Region"><?= h($r_address);?></textarea>
            </div>

            <!-- Business name -->
            <div class="form-group col-md-6">
              <label for="business_name">Business Name :</label>
              <div class="input-group with-icon">
                <span class="input-group-addon"><i class="fa fa-briefcase"></i></span>
                <input type="text" name="business_name" id="business_name" value="<?= h($business_name);?>" class="form-control" placeholder="Registered business (if any)">
              </div>
            </div>

            <!-- Business phone -->
            <div class="form-group col-md-6">
              <label for="business_phone">Business Phone :</label>
              <div class="input-group with-icon">
                <span class="input-group-addon"><i class="fa fa-phone-square"></i></span>
                <input type="tel" id="business_phone" value="<?= h($business_phone);?>" class="form-control phone" placeholder="Business phone">
              </div>
              <input type="hidden" name="business_phone" id="business_phone_hidden" value="">
            </div>

            <!-- Nature of business -->
            <div class="form-group col-md-6">
              <label for="nature_of_business">Nature of Business :</label>
              <div class="input-group with-icon">
                <span class="input-group-addon"><i class="fa fa-industry"></i></span>
                <input type="text" name="nature_of_business" id="nature_of_business" value="<?= h($nature_of_business);?>" class="form-control" placeholder="What do they do?">
              </div>
            </div>

            <!-- Document name -->
            <div class="form-group col-md-6">
              <label for="document_name">Name of Document :</label>
              <div class="input-group with-icon">
                <span class="input-group-addon"><i class="fa fa-id-card-o"></i></span>
                <input type="text" name="document_name" id="document_name" value="<?= h($document_name);?>" class="form-control" placeholder="e.g., Ghana Card, Passport">
              </div>
            </div>

            <!-- Attachment PDF -->
            <div class="form-group col-md-12">
              <label><i class="fa fa-file-pdf-o"></i> Attachment (PDF) <small class="text-muted">(optional)</small></label>
              <div class="file-zone">
                <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-upload"></i> Choose PDF
                </button>
                <span id="pdf_file_name" class="file-note">No file chosen yet.</span>
                <?php if(!empty($existing_attachment)){ ?>
                  <a class="btn btn-link" href="<?= h($existing_attachment);?>" target="_blank">
                    <i class="fa fa-external-link"></i> View current document
                  </a>
                <?php } ?>
              </div>
              <div class="help">Upload an ID/registration document (PDF only).</div>
            </div>

            <!-- Photo -->
            <div class="form-group col-md-12">
              <label for="uploaded_file"><?= h($_data['add_new_form_field_text_15']);?> :</label>
              <div class="media-row">
                <img class="avatar" src="<?= h($image_rnt);?>" id="output" alt="Tenant photo preview">
                <input type="hidden" name="img_exist" value="<?= h($img_track);?>">
                <div class="file-zone">
                  <input type="file" name="uploaded_file" id="uploaded_file" accept="image/png,image/jpeg,image/gif" class="form-control" style="display:none;" onchange="loadFile(event)">
                  <button type="button" class="btn btn-default" onclick="document.getElementById('uploaded_file').click();">
                    <i class="fa fa-image"></i> <?= h($_data['upload_image']);?>
                  </button>
                  <span class="file-note">Best results with a square image (JPEG/PNG/GIF).</span>
                </div>
              </div>
            </div>

          </div>

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

      </div>
    </div>
  </div>
</section>

<!-- ============== Scripts ============== -->
<script>
  // Gentle validation + capture intl phone values (falls back if plugin missing)
  function validateMe(){
    // Title/name check
    var name = (document.getElementById('txtRName').value || '').trim();
    if(!name){
      alert('Please enter the tenant’s full name.');
      document.getElementById('txtRName').focus();
      return false;
    }

    // Email: if present, validate format
    var emailEl = document.getElementById('txtREmail');
    if(emailEl && emailEl.value.trim() !== ''){
      var ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailEl.value.trim());
      if(!ok){ alert('Please provide a valid email or leave it blank.'); emailEl.focus(); return false; }
    }

    // Phone (primary) — required
    try{
      var inst = window.intlTelInputGlobals && window.intlTelInputGlobals.getInstance
                 ? window.intlTelInputGlobals.getInstance(document.getElementById('txtRContact'))
                 : null;
      document.getElementById('contact_hidden').value = inst ? inst.getNumber() : (document.getElementById('txtRContact').value || '');
      if(!document.getElementById('contact_hidden').value.trim()){
        alert('Please enter a valid phone number.');
        document.getElementById('txtRContact').focus();
        return false;
      }
    }catch(e){
      // fallback without plugin
      document.getElementById('contact_hidden').value = document.getElementById('txtRContact').value || '';
      if(!document.getElementById('contact_hidden').value.trim()){
        alert('Please enter a valid phone number.');
        document.getElementById('txtRContact').focus();
        return false;
      }
    }

    // Business phone (optional)
    try{
      var inst2 = window.intlTelInputGlobals && window.intlTelInputGlobals.getInstance
                  ? window.intlTelInputGlobals.getInstance(document.getElementById('business_phone'))
                  : null;
      document.getElementById('business_phone_hidden').value = inst2 ? inst2.getNumber() : (document.getElementById('business_phone').value || '');
    }catch(e){
      document.getElementById('business_phone_hidden').value = document.getElementById('business_phone').value || '';
    }

    return true;
  }

  // Image live preview
  function loadFile(event){
    var img = document.getElementById('output');
    if(event.target.files && event.target.files[0]){
      img.src = URL.createObjectURL(event.target.files[0]);
      img.onload = function(){ URL.revokeObjectURL(img.src); }
    }
  }

  // Show selected PDF file name
  (function(){
    var pdf = document.getElementById('pdf_attachment');
    if(!pdf) return;
    pdf.addEventListener('change', function(){
      var name = (this.files && this.files.length) ? this.files[0].name : 'No file chosen yet.';
      document.getElementById('pdf_file_name').textContent = name;
    });
  })();
</script>

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