<?php
require_once __DIR__ . '/../core/bootstrap.php';
Auth::requireRole('super_admin');
require_once __DIR__ . '/_layout.php';

$id = (int)e_get('id');
$site = null;

if ($id) {
    $st = db()->prepare("SELECT * FROM sites WHERE id = ? LIMIT 1");
    $st->execute([$id]);
    $site = $st->fetch();
    if (!$site) { flash('err', 'Site not found.'); redirect('sites.php'); }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();

    $domain = strtolower(trim(e_post('domain')));
    $domain = preg_replace('#^https?://#i', '', $domain);
    $domain = preg_replace('#^www\.#', '', $domain);
    $domain = preg_replace('#[/:].*$#', '', $domain);

    $company = e_post('company_name');

    if ($domain === '' || $company === '') {
        flash('err', 'Domain and company name are required.');
    } else {
        $dup = db()->prepare("SELECT id FROM sites WHERE domain = ?" . ($id ? " AND id <> ?" : "") . " LIMIT 1");
        $dup->execute($id ? [$domain, $id] : [$domain]);

        if ($dup->fetch()) {
            flash('err', 'Domain "' . $domain . '" is already used by another site.');
        } else {
            $fields = [
                'domain'             => $domain,
                'company_name'       => $company,
                'company_short_name' => e_post('company_short_name'),
                'company_number'     => e_post('company_number'),
                'year_founded'       => e_post('year_founded') !== '' ? (int)e_post('year_founded') : null,
                'theme_color'        => preg_match('/^#[0-9a-fA-F]{6}$/', e_post('theme_color')) ? e_post('theme_color') : '#0d6efd',
                'contact_email'      => e_post('contact_email'),
                'contact_phone'      => e_post('contact_phone'),
                'address_line1'      => e_post('address_line1'),
                'address_line2'      => e_post('address_line2'),
                'city'               => e_post('city'),
                'postcode'           => e_post('postcode'),
                'country'            => e_post('country') !== '' ? e_post('country') : 'United Kingdom',
                'is_active'          => isset($_POST['is_active']) ? 1 : 0,
            ];

            $logo = upload_image('logo', __DIR__ . '/../uploads/logos', 'logo');
            if ($logo) {
                if ($site && !empty($site['logo_path'])) {
                    $old = __DIR__ . '/../uploads/logos/' . basename($site['logo_path']);
                    if (is_file($old)) @unlink($old);
                }
                $fields['logo_path'] = $logo;
            }

            if ($id) {
                $set = implode(', ', array_map(fn($k) => "$k = ?", array_keys($fields)));
                db()->prepare("UPDATE sites SET $set WHERE id = ?")->execute([...array_values($fields), $id]);
                flash('ok', 'Site updated.');
            } else {
                $cols = implode(', ', array_keys($fields));
                $ph   = implode(', ', array_fill(0, count($fields), '?'));
                db()->prepare("INSERT INTO sites ($cols) VALUES ($ph)")->execute(array_values($fields));
                $id = (int)db()->lastInsertId();
                flash('ok', 'Site created. Download its satellite file from the list and upload it to that domain\'s hosting.');
            }
            redirect('sites.php');
        }
    }
}

$val = function ($k, $d = '') use ($site) { return $site[$k] ?? $d; };

admin_head($id ? 'Edit site' : 'New site');
admin_topbar($id ? 'Edit site' : 'New site', '<a href="sites.php" class="btn secondary">&larr; Back to sites</a>');
?>
<form method="post" enctype="multipart/form-data">
<?= csrf_field() ?>

<div class="card">
  <h2 style="margin-top:0;font-size:16px">Identity</h2>
  <label>Domain *</label>
  <input type="text" name="domain" required value="<?= h($val('domain')) ?>" placeholder="example-motors.co.uk">
  <p class="muted" style="margin:5px 0 0">Exactly as it appears in the address bar, without https:// and without www.</p>

  <div class="row2">
    <div><label>Company name *</label><input type="text" name="company_name" required value="<?= h($val('company_name')) ?>"></div>
    <div><label>Short name</label><input type="text" name="company_short_name" value="<?= h($val('company_short_name')) ?>"></div>
  </div>
  <div class="row2">
    <div><label>Company number</label><input type="text" name="company_number" value="<?= h($val('company_number')) ?>"></div>
    <div><label>Year founded</label><input type="number" name="year_founded" min="1900" max="2100" value="<?= h($val('year_founded')) ?>"></div>
  </div>
  <div class="row2">
    <div><label>Theme colour</label><input type="color" name="theme_color" value="<?= h($val('theme_color', '#0d6efd')) ?>"></div>
    <div>
      <label>Logo</label>
      <input type="file" name="logo" accept="image/jpeg,image/png,image/webp">
      <?php if ($val('logo_path')): ?>
        <div style="margin-top:8px"><img class="thumb" src="../uploads/logos/<?= h($val('logo_path')) ?>" alt=""></div>
      <?php endif; ?>
    </div>
  </div>
  <label style="display:flex;align-items:center;gap:8px;margin-top:14px">
    <input type="checkbox" name="is_active" value="1" <?= $val('is_active', 1) ? 'checked' : '' ?>>
    Site active (when unticked, the domain shows an unavailable message)
  </label>
</div>

<div class="card">
  <h2 style="margin-top:0;font-size:16px">Contact and address</h2>
  <p class="muted" style="margin:0 0 10px">Shown publicly on the satellite site. Enquiries from that domain arrive at this email address.</p>
  <div class="row2">
    <div><label>Contact email</label><input type="email" name="contact_email" value="<?= h($val('contact_email')) ?>"></div>
    <div><label>Phone</label><input type="text" name="contact_phone" value="<?= h($val('contact_phone')) ?>"></div>
  </div>
  <label>Address line 1</label><input type="text" name="address_line1" value="<?= h($val('address_line1')) ?>">
  <label>Address line 2</label><input type="text" name="address_line2" value="<?= h($val('address_line2')) ?>">
  <div class="row2">
    <div><label>City</label><input type="text" name="city" value="<?= h($val('city')) ?>"></div>
    <div><label>Postcode</label><input type="text" name="postcode" value="<?= h($val('postcode')) ?>"></div>
  </div>
  <label>Country</label><input type="text" name="country" value="<?= h($val('country', 'United Kingdom')) ?>">
</div>

<div class="card">
  <button class="btn" type="submit"><?= $id ? 'Save changes' : 'Create site' ?></button>
</div>
</form>
<?php admin_foot(); ?>
