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

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}
if (isset($_SESSION['login_type']) && $_SESSION['login_type'] !== "super") {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

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

/* ----------------- Defaults ----------------- */
$title                     = $_data['text_1'];
$button_text               = $_data['save_button_text'];
$successful_msg            = $_data['text_11'];
$form_url                  = WEB_URL . "branch/addbranch.php";
$hdnid                     = "0";

$branch_name               = '';
$b_email                   = '';
$b_contact_no              = '';
$b_address                 = '';
$security_guard_mobile     = '';
$secrataty_mobile          = '';
$moderator_mobile          = '';
$building_make_year        = '';
$builder_company_name      = '';
$builder_company_phone     = '';
$builder_company_address   = '';
$building_rule             = '';
$b_status                  = 1;

$image_building            = WEB_URL . 'img/no_image.jpg';
$img_track                 = '';

/* ----------------- Edit Mode Prefill ----------------- */
if (isset($_GET['id']) && $_GET['id'] !== '') {
  $id = (int)$_GET['id'];
  $res = mysqli_query($link, "SELECT * FROM tblbranch WHERE branch_id = {$id}");
  if ($row = mysqli_fetch_assoc($res)) {
    $branch_name             = $row['branch_name'];
    $b_email                 = $row['b_email'];
    $b_contact_no            = $row['b_contact_no'];
    $b_address               = $row['b_address'];
    $security_guard_mobile   = $row['security_guard_mobile'];
    $secrataty_mobile        = $row['secrataty_mobile'];
    $moderator_mobile        = $row['moderator_mobile'];
    $building_make_year      = $row['building_make_year'];
    $builder_company_name    = $row['builder_company_name'];
    $builder_company_phone   = $row['builder_company_phone'];
    $builder_company_address = $row['builder_company_address'];
    $building_rule           = $row['building_rule'];
    $b_status                = (int)$row['b_status'];

    if (!empty($row['building_image'])) {
      $image_building = WEB_URL . 'img/upload/' . $row['building_image'];
      $img_track      = $row['building_image'];
    }
    $hdnid          = (string)$id;
    $title          = $_data['text_1_1'];
    $button_text    = $_data['update_button_text'];
    $successful_msg = $_data['text_12'];
    $form_url       = WEB_URL . "branch/addbranch.php?id={$id}";
  }
}

/* ----------------- File upload helper ----------------- */
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 a new file was posted, save it; otherwise keep existing
  if (!empty($_FILES['uploaded_file']) && isset($_FILES['uploaded_file']['error']) && $_FILES['uploaded_file']['error'] === UPLOAD_ERR_OK) {
    $filename = basename($_FILES['uploaded_file']['name']);
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $okExt = in_array($ext, ['jpg','jpeg','png','gif']);
    if ($okExt && is_uploaded_file($_FILES['uploaded_file']['tmp_name'])) {
      // Build a robust upload path (works on Windows/XAMPP and Linux)
      $uploadDir = rtrim(ROOT_PATH, "/\\") . '/img/upload/';
      if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0777, true);
      }
      $newfilename = NewGuid() . '.' . $ext;
      $dest = $uploadDir . $newfilename;
      if (@move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $dest)) {
        return $newfilename; // store only the filename in DB
      }
    }
    // if something failed, fall back to existing (don’t blank the image)
    return isset($_POST['img_exist']) ? $_POST['img_exist'] : '';
  }
  // No new file selected -> keep existing
  return isset($_POST['img_exist']) ? $_POST['img_exist'] : '';
}

/* ----------------- Handle POST ----------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['txtBrName'])) {
  $image_url = uploadImage();

  $branch_name_in   = $_POST['txtBrName'] ?? '';
  $b_email_in       = $_POST['txtBrEmail'] ?? '';
  $b_contact_no_in  = $_POST['txtBrConNo'] ?? '';
  $b_address_in     = $_POST['txtareaAddress'] ?? '';
  $sec_guard_in     = $_POST['security_guard_mobile'] ?? '';
  $secrataty_in     = $_POST['secrataty_mobile'] ?? '';
  $moderator_in     = $_POST['moderator_mobile'] ?? '';
  $make_year_in     = $_POST['building_make_year'] ?? '';
  $b_status_in      = isset($_POST['radioStatus']) ? (int)$_POST['radioStatus'] : 1;
  $builder_name_in  = $_POST['builder_company_name'] ?? '';
  $builder_phone_in = $_POST['builder_company_phone'] ?? '';
  $builder_addr_in  = $_POST['builder_company_address'] ?? '';
  $rule_in          = $_POST['building_rule'] ?? '';

  if (isset($_POST['hdn']) && $_POST['hdn'] === '0') {
    // INSERT — FIXED types (image is string, status is int)
    $sql = "INSERT INTO tblbranch
      (branch_name, b_email, b_contact_no, b_address, security_guard_mobile, secrataty_mobile, moderator_mobile, building_make_year, building_image, b_status, builder_company_name, builder_company_phone, builder_company_address, building_rule)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = mysqli_prepare($link, $sql);
    mysqli_stmt_bind_param(
      $stmt, "sssssssssissss",
      $branch_name_in, $b_email_in, $b_contact_no_in, $b_address_in,
      $sec_guard_in, $secrataty_in, $moderator_in, $make_year_in,
      $image_url,            // s (WAS wrongly bound as i)
      $b_status_in,          // i
      $builder_name_in, $builder_phone_in, $builder_addr_in, $rule_in
    );
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    mysqli_close($link);
    header("Location: " . WEB_URL . "branch/branchlist.php?m=add");
    exit;
  } else {
    // UPDATE — FIXED types (image is string, status is int)
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $sql = "UPDATE tblbranch SET
      branch_name = ?, b_email = ?, b_contact_no = ?, b_address = ?,
      security_guard_mobile = ?, secrataty_mobile = ?, moderator_mobile = ?,
      building_make_year = ?, building_image = ?, b_status = ?,
      builder_company_name = ?, builder_company_phone = ?, builder_company_address = ?,
      building_rule = ?
      WHERE branch_id = ?";
    $stmt = mysqli_prepare($link, $sql);
    mysqli_stmt_bind_param(
      $stmt, "sssssssssissssi",
      $branch_name_in, $b_email_in, $b_contact_no_in, $b_address_in,
      $sec_guard_in, $secrataty_in, $moderator_in, $make_year_in,
      $image_url,            // s (WAS wrongly bound as i)
      $b_status_in,          // i
      $builder_name_in, $builder_phone_in, $builder_addr_in, $rule_in,
      $id                    // i
    );
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    mysqli_close($link);
    header("Location: " . WEB_URL . "branch/branchlist.php?m=up");
    exit;
  }
}
?>
<!-- Content Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <i class="fa fa-building"></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><a href="<?= WEB_URL?>branch/branchlist.php"><?= e($_data['text_2']);?></a></li>
    <li class="active"><?= e($_data['text_1']);?></li>
  </ol>
</section>

<!-- Styles (modern, clean, friendly) -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --bg:#f8fafc; --bg2:#eef2ff;
    --ink:#0f172a; --muted:#64748b; --line:#e5e7eb;
    --brand:#111827; --ok:#16a34a; --warn:#d97706;
  }
  body, .content-wrapper { font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial; color:var(--ink); }
  .box.box-success{
    border-radius:16px; border:1px solid var(--line); overflow:hidden;
    box-shadow:0 18px 48px rgba(2,6,23,.08);
  }
  .box.box-success .box-header{
    background:linear-gradient(135deg,var(--bg),var(--bg2)); border-bottom:1px solid var(--line);
    padding:14px 16px;
  }
  .box.box-success .box-title{ font-weight:800; letter-spacing:.2px; color:var(--ink); }

  label{ font-weight:700; color:#111827; }
  .form-control{
    border-radius:12px; border:1px solid var(--line); box-shadow:none !important;
  }
  .help{ font-size:12px; color:#muted; }

  /* Status radio as pill toggle */
  .status-wrap{ display:flex; gap:10px; flex-wrap:wrap; }
  .status-pill{
    display:inline-flex; align-items:center; gap:8px; padding:8px 12px; border-radius:999px;
    border:1px solid var(--line); background:#fff; cursor:pointer; font-weight:700;
  }
  .status-pill input{ display:none; }
  .status-pill.active{ border-color:#22c55e; background:#ecfdf5; color:#065f46; }

  /* Building image preview */
  .large-thumbnail{
    width:100%; height:220px; object-fit:cover; border:1px solid var(--line); border-radius:12px;
    background:#fff;
  }

  /* Section titles */
  .section-label{
    margin:6px 0 10px; font-weight:800; font-size:16px; color:#0f172a;
    border-bottom:1px solid var(--line); padding-bottom:6px;
    display:flex; align-items:center; gap:8px;
  }

  /* Buttons */
  .btn-success{ background:#111827; border-color:#111827; border-radius:10px; font-weight:800; }
  .btn-success:hover{ filter:brightness(1.05); }
  .btn-warning{ border-radius:10px; font-weight:800; }
</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['text_3']); ?></h3>
        </div>

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

            <!-- Left column -->
            <div class="col-md-6">

              <div class="form-group col-md-12">
                <label for="txtBrName"><span class="text-danger">*</span> <?= e($_data['text_4']); ?>:</label>
                <input type="text" name="txtBrName" id="txtBrName" class="form-control" value="<?= e($branch_name); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="txtBrEmail"><span class="text-danger">*</span> <?= e($_data['text_5']); ?>:</label>
                <input type="email" name="txtBrEmail" id="txtBrEmail" class="form-control" required value="<?= e($b_email); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="txtBrConNo"><span class="text-danger">*</span> <?= e($_data['text_6']); ?>:</label>
                <input type="text" name="txtBrConNo" id="txtBrConNo" class="form-control" value="<?= e($b_contact_no); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="security_guard_mobile"><?= e($_data['text_14']); ?>:</label>
                <input type="text" name="security_guard_mobile" id="security_guard_mobile" class="form-control" value="<?= e($security_guard_mobile); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="secrataty_mobile"><?= e($_data['text_secretary_mobile'] ?? 'Secretary Mobile'); ?>:</label>
                <input type="text" name="secrataty_mobile" id="secrataty_mobile" class="form-control" value="<?= e($secrataty_mobile); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="moderator_mobile"><?= e($_data['text_moderator_mobile'] ?? 'Moderator Mobile'); ?>:</label>
                <input type="text" name="moderator_mobile" id="moderator_mobile" class="form-control" value="<?= e($moderator_mobile); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="txtareaAddress"><span class="text-danger">*</span> <?= e($_data['text_7']); ?>:</label>
                <textarea rows="3" name="txtareaAddress" id="txtareaAddress" class="form-control"><?= e($b_address); ?></textarea>
              </div>

              <div class="form-group col-md-12">
                <label><?= e($_data['text_8']); ?>:</label>
                <div class="status-wrap">
                  <?php
                    $active  = ($b_status == 1);
                    $inactive= ($b_status == 0);
                  ?>
                  <label class="status-pill <?= $active?'active':''; ?>">
                    <input type="radio" name="radioStatus" value="1" <?= $active?'checked':''; ?> />
                    <i class="fa fa-check-circle"></i> <?= e($_data['text_9']); ?>
                  </label>

                  <label class="status-pill <?= $inactive?'active':''; ?>">
                    <input type="radio" name="radioStatus" value="0" <?= $inactive?'checked':''; ?> />
                    <i class="fa fa-ban"></i> <?= e($_data['text_10']); ?>
                  </label>
                </div>
                <div class="help"><?= e($_data['text_status_help'] ?? 'Choose whether this branch is active.'); ?></div>
              </div>
            </div>

            <!-- Right column -->
            <div class="col-md-6">

              <div class="form-group col-md-6">
                <label for="Prsnttxtarea"><?= e($_data['text_18']); ?>:</label>
                <img class="form-control large-thumbnail" src="<?= e($image_building); ?>" id="output" alt="building preview">
                <input type="hidden" name="img_exist" value="<?= e($img_track); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label><?= e($_data['upload_image']); ?></label><br>
                <span class="btn btn-default btn-file" style="border-radius:10px;border:1px solid var(--line);">
                  <i class="fa fa-upload"></i> <?= e($_data['upload_image']); ?>
                  <input type="file" name="uploaded_file" accept="image/*" onchange="loadFile(event)">
                </span>
                <div class="help" style="margin-top:6px;">JPG, PNG, GIF · Recommended min height 220px</div>
              </div>

              <div class="form-group col-md-12">
                <label for="building_make_year"><?= e($_data['text_build_year'] ?? 'Building Make Year'); ?>:</label>
                <input type="text" name="building_make_year" id="building_make_year" class="form-control" value="<?= e($building_make_year); ?>" />
              </div>

              <div class="form-group col-md-12">
                <div class="section-label"><i class="fa fa-industry"></i> <?= e($_data['text_builder_info'] ?? 'Builder Company Information'); ?></div>
              </div>

              <div class="form-group col-md-12">
                <label for="builder_company_name"><?= e($_data['text_builder_name'] ?? 'Company Name'); ?>:</label>
                <input type="text" name="builder_company_name" id="builder_company_name" class="form-control" value="<?= e($builder_company_name); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="builder_company_phone"><?= e($_data['text_builder_phone'] ?? 'Company Phone'); ?>:</label>
                <input type="text" name="builder_company_phone" id="builder_company_phone" class="form-control" value="<?= e($builder_company_phone); ?>" />
              </div>

              <div class="form-group col-md-12">
                <label for="builder_company_address"><?= e($_data['text_builder_address'] ?? 'Company Address'); ?>:</label>
                <textarea rows="2" name="builder_company_address" id="builder_company_address" class="form-control"><?= e($builder_company_address); ?></textarea>
              </div>
            </div>

            <div class="col-md-12">
              <div class="section-label"><i class="fa fa-list-alt"></i> <?= e($_data['text_23']); ?></div>
              <div class="form-group">
                <label for="building_rule"><?= e($_data['text_24']); ?>:</label>
                <textarea name="building_rule" id="building_rule" class="form-control"><?= e($building_rule); ?></textarea>
              </div>
            </div>

          </div><!-- /.box-body -->

          <div class="box-footer" style="display:flex;justify-content:flex-end;gap:10px;">
            <button type="submit" class="btn btn-success">
              <i class="fa fa-floppy-o"></i> <?= e($button_text); ?>
            </button>
            <a class="btn btn-warning" href="<?= WEB_URL; ?>branch/branchlist.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">
  // live image preview
  function loadFile(e){
    var out = document.getElementById('output');
    if (out && e.target && e.target.files && e.target.files[0]) {
      out.src = URL.createObjectURL(e.target.files[0]);
    }
  }

  // status pill UI
  document.addEventListener('change', function(ev){
    if (ev.target && ev.target.name === 'radioStatus') {
      document.querySelectorAll('.status-pill').forEach(function(p){ p.classList.remove('active'); });
      ev.target.closest('.status-pill').classList.add('active');
    }
  });

  function validateMe(){
    if(document.getElementById('txtBrName').value.trim() === ''){
      alert("<?= e($_data['r1']); ?>"); document.getElementById('txtBrName').focus(); return false;
    }
    if(document.getElementById('txtBrEmail').value.trim() === ''){
      alert("<?= e($_data['r2']); ?>"); document.getElementById('txtBrEmail').focus(); return false;
    }
    if(document.getElementById('txtBrConNo').value.trim() === ''){
      alert("<?= e($_data['r3']); ?>"); document.getElementById('txtBrConNo').focus(); return false;
    }
    if(document.getElementById('txtareaAddress').value.trim() === ''){
      alert("<?= e($_data['r4']); ?>"); document.getElementById('txtareaAddress').focus(); return false;
    }
    return true;
  }

  // CKEditor (keep your original behavior)
  if (typeof CKEDITOR !== 'undefined') {
    CKEDITOR.replace('building_rule', { height: 700 });
  }
</script>

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