<?php
include_once('../header.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_add_unit.php');

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

/* -------------------------------
   Helpers & Defaults
-------------------------------- */
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$success        = "none";
$b_name         = '';
$unit_no        = '';
$rate           = '';
$d_rate         = '';
$rate_currency  = '';
$floor          = '';
$bid            = '';
$title          = $_data['add_new_unit'];
$button_text    = $_data['save_button_text'];
$successful_msg = $_data['add_unit_successfully'];
$form_url       = WEB_URL . "unit/addunit.php";
$hdnid          = "0";
$viewOnly       = (isset($_GET['mode']) && $_GET['mode'] === 'view'); // read-only mode
$disabledAttr   = $viewOnly ? 'disabled' : '';

/* Fetch currencies once for selects */
$currencies = [];
if ($resCur = mysqli_query($link, "SELECT cid, symbol FROM currencies ORDER BY cid ASC")) {
  while ($rowCur = mysqli_fetch_assoc($resCur)) { $currencies[] = $rowCur; }
  mysqli_free_result($resCur);
}

/* Fetch blocks once for selects */
$blocks = [];
if ($resBlocks = mysqli_query($link, "SELECT bid, b_name FROM blocks ORDER BY b_name ASC")) {
  while ($rb = mysqli_fetch_assoc($resBlocks)) {
    $blocks[] = ['bid' => (int)$rb['bid'], 'b_name' => $rb['b_name']];
  }
  mysqli_free_result($resBlocks);
}

/* -------------------------------
   Handle POST (Create / Update)
-------------------------------- */
if (isset($_POST['txtUnit'])) {
  $post_bid      = mysqli_real_escape_string($link, $_POST['bid']);
  $post_unit     = mysqli_real_escape_string($link, $_POST['txtUnit']);
  $post_rate     = mysqli_real_escape_string($link, $_POST['rate']);
  $post_d_rate   = mysqli_real_escape_string($link, $_POST['d_rate']);
  $post_rate_cur = mysqli_real_escape_string($link, $_POST['rate_currency']);
  $post_floor    = mysqli_real_escape_string($link, $_POST['floor']);

  if (isset($_POST['hdn']) && $_POST['hdn'] == '0') {
    // Create
    $sql = "INSERT INTO `units` (bid, unit_no, rate, d_rate, rate_currency_id, floor)
            VALUES ('$post_bid', '$post_unit', '$post_rate', '$post_d_rate', '$post_rate_cur', '$post_floor')";
    mysqli_query($link, $sql);
    mysqli_close($link);
    header("Location: " . WEB_URL . 'unit/unitlist.php?m=add');
    exit;
  } else {
    // Update
    $uid = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $sql = "UPDATE `units`
            SET bid = '$post_bid',
                unit_no = '$post_unit',
                rate = '$post_rate',
                d_rate = '$post_d_rate',
                rate_currency_id = '$post_rate_cur',
                floor = '$post_floor'
            WHERE uid = '$uid'";
    mysqli_query($link, $sql);
    mysqli_close($link);
    header("Location: " . WEB_URL . 'unit/unitlist.php?m=up');
    exit;
  }
  $success = "block";
}

/* -------------------------------
   Edit Mode (prefill)
-------------------------------- */
if (isset($_GET['id']) && $_GET['id'] !== '') {
  $q = "SELECT * FROM unit_view WHERE uid = '" . mysqli_real_escape_string($link, $_GET['id']) . "'";
  if ($result = mysqli_query($link, $q)) {
    if ($row = mysqli_fetch_array($result)) {
      $bid           = $row["bid"];
      $floor         = $row["floor"];
      $b_name        = $row['b_name'];
      $rate_currency = $row['rate_currency_id'];
      $rate          = $row["rate"];
      $d_rate        = $row["d_rate"];
      $unit_no       = $row['unit_no'];
      $hdnid         = $_GET['id'];
      $title         = $_data['update_unit'];
      $button_text   = $_data['update_button_text'];
      $successful_msg= $_data['update_unit_successfully'];
      $form_url      = WEB_URL . "unit/addunit.php?id=" . $_GET['id'];
    }
    mysqli_free_result($result);
  }
}

if ($viewOnly) {
  $title = 'View Unit Details';
}

/* Helper: current currency symbol for initial load */
function currentSymbol($currencies, $rate_currency){
  foreach($currencies as $c){
    if ((string)$c['cid'] === (string)$rate_currency) return $c['symbol'];
  }
  return isset($currencies[0]['symbol']) ? $currencies[0]['symbol'] : '$';
}
$curSymbol = currentSymbol($currencies, $rate_currency);
?>
<!-- Content Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;font-weight:800;">
    <i class="fa fa-cube"></i> <?= e($title); ?>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL?>dashboard.php"><i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']);?></a></li>
    <li class="active"><?= e($_data['add_new_unit_information_breadcam']);?></li>
    <li class="active"><?= e($title);?></li>
  </ol>
</section>

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

  /* Card */
  .box.box-success{
    border-radius:16px; overflow:hidden; border:1px solid var(--line);
    box-shadow:0 12px 32px rgba(2,6,23,.08);
  }
  .box .box-header{
    background:linear-gradient(135deg,var(--soft),var(--soft2));
    border-bottom:1px solid var(--line);
  }
  .box .box-title{ font-weight:800; color:var(--ink); display:flex; align-items:center; gap:8px; }

  /* Form */
  .form-group label{ font-weight:700; color:var(--ink); }
  .form-control{
    height:44px; border-radius:12px; border:1px solid var(--line-2);
    box-shadow:none !important;
  }
  .form-control[disabled], .form-control[readonly]{ background:#f9fafb; cursor:not-allowed; }
  textarea.form-control{ height:auto; min-height:100px; padding-top:10px; }

  .input-group-addon{
    background:var(--white); border:1px solid var(--line-2); border-right:0;
    border-radius:12px 0 0 12px; color:#475569; min-width:52px; text-align:center;
  }
  .with-addon .form-control{ border-left:0; border-radius:0 12px 12px 0; }

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

  /* Buttons */
  .btn{ border-radius:10px; font-weight:700; }
  .btn-success{ background:var(--ok); border-color:var(--ok); }
  .btn-success:hover{ background:#15803d; border-color:#15803d; }
  .btn-warning{ background:#f59e0b; border-color:#f59e0b; }
  .btn-warning:hover{ background:#d97706; border-color:#d97706; }

  /* Section helper */
  .section-hint{
    font-size:12px; color:var(--muted); background:#f1f5f9;
    border:1px solid var(--line); padding:10px 12px; border-radius:12px; margin:0 18px 14px;
  }
</style>

<!-- Main content -->
<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-info-circle"></i> <?= e($_data['add_new_unit_entry_form']);?>
          </h3>
        </div>

        <div class="section-hint">
          <strong>Tip:</strong> Choose a block first, then enter the unit/shop number. The selected <em>Currency</em> applies to both Daily and Monthly rates.
        </div>

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

            <!-- Block -->
            <div class="form-group col-sm-6">
              <label for="b_name"><span class="errorStar">*</span> <?= e($_data['add_new_form_field_text_1']);?> :</label>
              <select <?= $disabledAttr; ?> onchange="getActiveUnit && getActiveUnit(this.value);" name="bid" id="b_name" class="form-control" required>
                <option value="">-- <?= e($_data['add_new_form_field_text_1']);?> --</option>
                <?php foreach ($blocks as $b): ?>
                  <option value="<?= (int)$b['bid']; ?>" <?= ((string)$bid === (string)$b['bid'] ? 'selected' : ''); ?>>
                    <?= e($b['b_name']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="help-text"><?= e($_data['add_new_form_field_text_1']);?> is required.</div>
            </div>

            <!-- Unit / Shop number -->
            <div class="form-group col-sm-6">
              <label for="txtUnit"><span class="errorStar">*</span> <?= e($_data['add_new_form_field_text_2']);?> :</label>
              <input <?= $disabledAttr; ?> type="text" name="txtUnit" value="<?= e($unit_no);?>" id="txtUnit" class="form-control" required placeholder="e.g., A-12 / Shop 5" />
            </div>

            <!-- Floor -->
            <div class="form-group col-sm-6">
              <label for="floor"><span class="errorStar">*</span> Floor :</label>
              <select <?= $disabledAttr; ?> name="floor" id="floor" class="form-control" required>
                <option value="">-- Select Floor --</option>
                <?php
                  $floors = [
                    "Ground Floor",
                    "First Floor",
                    "Second Floor",
                    "Third Floor",
                    "Fourth Floor",
                    "Fifth Floor",
                    "Sixth Floor",
                    "Seventh Floor",
                    "Eighth Floor"
                    
                  ];
                  foreach($floors as $f){
                    $sel = ($floor === $f) ? 'selected' : '';
                    echo '<option value="'.e($f).'" '.$sel.'>'.e($f).'</option>';
                  }
                ?>
              </select>
            </div>

            <!-- Currency -->
            <div class="form-group col-sm-6">
              <label for="rate_currency"><span class="errorStar">*</span> Currency :</label>
              <select <?= $disabledAttr; ?> class="form-control" name="rate_currency" id="rate_currency" required>
                <?php foreach($currencies as $c): ?>
                  <option value="<?= (int)$c['cid']; ?>" data-symbol="<?= e($c['symbol']); ?>" <?= ($rate_currency == $c['cid'] ? 'selected' : '') ?>>
                    <?= e($c['symbol']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="help-text">Applies to both daily and monthly rates.</div>
            </div>

            <!-- Daily Rate -->
            <div class="form-group col-sm-6">
              <label for="d_rate"><span class="errorStar">*</span> Daily Rate:</label>
              <div class="input-group with-addon">
                <div class="input-group-addon"><span class="cur-symbol"><?= e($curSymbol); ?></span></div>
                <input <?= $disabledAttr; ?> type="number" min="0" step="0.01" name="d_rate" value="<?= e($d_rate ?? "");?>" id="d_rate" class="form-control" required placeholder="0.00" />
              </div>
            </div>

            <!-- Monthly Rate -->
            <div class="form-group col-sm-6">
              <label for="rate"><span class="errorStar">*</span> Monthly Rate :</label>
              <div class="input-group with-addon">
                <div class="input-group-addon"><span class="cur-symbol"><?= e($curSymbol); ?></span></div>
                <input <?= $disabledAttr; ?> type="number" min="0" step="0.01" name="rate" value="<?= e($rate ?? "");?>" id="rate" class="form-control" required placeholder="0.00" />
              </div>
            </div>

          </div>

          <div class="box-footer" style="padding:16px 18px; display:flex; justify-content:flex-end; gap:8px;">
            <?php if (!$viewOnly): ?>
              <button type="submit" name="submit" class="btn btn-success">
                <i class="fa fa-floppy-o"></i> <?= e($button_text); ?>
              </button>
            <?php endif; ?>
            <a class="btn btn-warning" href="<?= WEB_URL; ?>unit/unitlist.php">
              <i class="fa fa-reply"></i> <?= e($_data['back_text']);?>
            </a>
          </div>

          <input type="hidden" value="<?= e($hdnid); ?>" name="hdn"/>
        </form>
      </div>
    </div>
  </div>
</section>

<script type="text/javascript">
  function validateMe(){
    var b = document.getElementById('b_name');
    var u = document.getElementById('txtUnit');
    var f = document.getElementById('floor');
    if(!b || !u || !f) return true;

    if(b.value === ''){
      alert("<?= e($_data['add_new_form_field_text_1']);?> is required");
      b.focus(); return false;
    }
    if(u.value.trim() === ''){
      alert("<?= e($_data['unit_required']); ?>");
      u.focus(); return false;
    }
    if(f.value === ''){
      alert("<?= e($_data['floor_required']); ?>");
      f.focus(); return false;
    }
    return true;
  }

  // Live update currency symbol on rate inputs
  (function(){
    var sel   = document.getElementById('rate_currency');
    var spans = document.querySelectorAll('.cur-symbol');
    if(!sel) return;
    sel.addEventListener('change', function(){
      var opt = sel.options[sel.selectedIndex];
      var sym = opt.getAttribute('data-symbol') || '';
      Array.prototype.forEach.call(spans, function(s){ s.textContent = sym; });
    });
  })();
</script>

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