<?php
$page_title = 'بيانات الشركة';

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidCompanyAdmin = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = $uaAndroidCompanyAdmin
  ? ['assets/css/company_admin.css', 'assets/css/android_company_admin.css']
  : ['assets/css/company_admin.css'];
require_once __DIR__ . '/header.php';
if (!defined('UA_EMBED') || !UA_EMBED) require_once __DIR__ . '/sidebar.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/company_profile_lib.php';
require_once __DIR__ . '/device_admin_alerts_lib.php';

require_login();

$conn = ensure_db(true);

$table = company_profile_ensure_schema($conn);
device_admin_alerts_ensure_schema($conn);
$msg = '';
$err = '';

if ($table === '') {
  $err = 'لا يوجد جدول لإعدادات الشركة (company_info أو system_settings).';
} else {
  if (isset($_POST['save'])) {
    $company_name = trim((string)($_POST['company_name'] ?? ''));
    $owner_name   = trim((string)($_POST['owner_name'] ?? ''));
    $phone        = trim((string)($_POST['phone'] ?? ''));
    $address      = trim((string)($_POST['address'] ?? ''));
    $admin_alert_phones = trim((string)($_POST['admin_alert_phones'] ?? ''));
    $contacts     = company_profile_contacts_from_post($_POST);
    $contactsJson = json_encode($contacts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if (!is_string($contactsJson)) $contactsJson = '[]';

    $conn->query("INSERT INTO `$table` (id) SELECT 1 WHERE NOT EXISTS(SELECT 1 FROM `$table` WHERE id=1)");
    $stmt = $conn->prepare("UPDATE `$table` SET company_name=?, owner_name=?, phone=?, address=?, contact_methods_json=?, admin_alert_phones=? WHERE id=1");
    if ($stmt) {
      $stmt->bind_param('ssssss', $company_name, $owner_name, $phone, $address, $contactsJson, $admin_alert_phones);
      if ($stmt->execute()) $msg = 'تم حفظ بيانات الشركة ووسائل التواصل.';
      else $err = 'تعذر حفظ بيانات الشركة.';
      $stmt->close();
    } else {
      $err = 'تعذر تجهيز عملية الحفظ.';
    }
  }

  $row = $conn->query("SELECT * FROM `$table` WHERE id=1 LIMIT 1");
  $row = $row && $row->num_rows ? $row->fetch_assoc() : [];
}
$companyContacts = company_profile_contacts_decode($row['contact_methods_json'] ?? '');
$contactTypes = company_profile_contact_types();

$active_tab = 'company';
if ($uaAndroidCompanyAdmin) {
  require __DIR__ . '/android_company_admin.php';
  ?><script src="assets/js/company_contacts.js?v=<?= (int)(@filemtime(__DIR__ . '/assets/js/company_contacts.js') ?: 1) ?>"></script><?php
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid">
      <h1 class="mb-0">بيانات الشركة</h1>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php if (!defined('UA_EMBED') || !UA_EMBED) require __DIR__ . '/settings_tabs.php'; ?>
      <?php if($msg){ ?><div class="alert alert-success"><?= h($msg) ?></div><?php } ?>
      <?php if($err){ ?><div class="alert alert-danger"><?= h($err) ?></div><?php } ?>

      <?php if(!$err){ ?>
      <div class="card">
        <div class="card-body">
          <form method="post">
            <div class="row">
              <div class="col-md-6">
                <div class="form-group">
                  <label>اسم الشركة</label>
                  <input name="company_name" class="form-control" value="<?= h($row['company_name'] ?? '') ?>">
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <label>اسم مالك الشركة</label>
                  <input name="owner_name" class="form-control" value="<?= h($row['owner_name'] ?? '') ?>">
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col-md-6">
                <div class="form-group">
                  <label>هاتف</label>
                  <input name="phone" class="form-control" value="<?= h($row['phone'] ?? '') ?>">
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <label>العنوان</label>
                  <input name="address" class="form-control" value="<?= h($row['address'] ?? '') ?>">
                </div>
              </div>
            </div>

            <?php require __DIR__ . '/partials/company_contact_fields.php'; ?>

            <div class="form-group mt-3">
              <label>أرقام تنبيهات الإدارة</label>
              <textarea name="admin_alert_phones" class="form-control" rows="3" dir="ltr" placeholder="9639XXXXXXXX، رقم في كل سطر"><?= h($row['admin_alert_phones'] ?? '') ?></textarea>
              <small class="form-text text-muted">تُرسل إليها تنبيهات انقطاع أجهزة الشبكة وعودتها. افصل الأرقام بسطر جديد أو فاصلة.</small>
            </div>

            <button class="btn btn-success mt-3" name="save"><i class="fa fa-save"></i> حفظ بيانات الشركة</button>
          </form>
        </div>
      </div>
      <?php } ?>

    </div>
  </section>
</div>
<script src="assets/js/company_contacts.js?v=<?= (int)(@filemtime(__DIR__ . '/assets/js/company_contacts.js') ?: 1) ?>"></script>
<?php include __DIR__ . '/footer.php'; ?>
