<?php
require_once __DIR__ . '/../includes/lang.php';
require_once __DIR__ . '/../config/db.php';
session_start();
if (isset($_SESSION['user_id'])) { header('Location: ../dashboard.php'); exit; }
$dir  = t('dir');
$code = t('lang_code');

$activityType = trim($_GET['activity'] ?? $_POST['activity_type'] ?? 'restaurant');
$allowed_types = ['restaurant','hotel','guide','craft','agency','transport'];
if (!in_array($activityType, $allowed_types)) $activityType = 'restaurant';

$act_icons = [
    'restaurant'=>'🍽️','hotel'=>'🏨','guide'=>'🗺️',
    'craft'=>'🛍️','agency'=>'✈️','transport'=>'🚲'
];
$act_labels = [
    'restaurant'=>t('act_restaurant'),'hotel'=>t('act_hotel'),
    'guide'=>t('act_guide'),'craft'=>t('act_craft'),
    'agency'=>t('act_agency'),'transport'=>t('act_transport')
];

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username   = trim($_POST['username'] ?? '');
    $biz_name   = trim($_POST['biz_name'] ?? '');
    $password   = $_POST['password'] ?? '';
    $confirm    = $_POST['confirm'] ?? '';
    $email      = trim($_POST['email'] ?? '');
    $phone      = trim($_POST['phone'] ?? '');
    $address    = trim($_POST['address'] ?? '');
    $lat        = $_POST['lat'] ?? null;
    $lng        = $_POST['lng'] ?? null;
    $desc       = trim($_POST['description'] ?? '');
    $terms      = isset($_POST['terms']);
    $act_type   = $activityType;

    if (!$username || !$biz_name || !$password || !$email || !$phone) {
        $error = t('err_required');
    } elseif ($password !== $confirm) {
        $error = t('err_pass_match');
    } elseif (!$terms) {
        $error = t('err_terms');
    } else {
        $ch = db()->prepare("SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1");
        $ch->execute([$username, $email]);
        if ($ch->fetch()) {
            $error = t('err_username_taken');
        } else {
            $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
            db()->beginTransaction();
            try {
                $ins = db()->prepare("INSERT INTO users (username, email, password_hash, role) VALUES (?,?,?,'provider')");
                $ins->execute([$username, $email, $hash]);
                $user_id = db()->lastInsertId();

                $image = upload_image('image', 'activities');

                $ins2 = db()->prepare("INSERT INTO providers (user_id, business_name, activity_type, email, phone, address, lat, lng, image, description, status) VALUES (?,?,?,?,?,?,?,?,?,?,'pending')");
                $ins2->execute([
                    $user_id, $biz_name, $act_type, $email, $phone,
                    $address ?: null,
                    $lat ? (float)$lat : null,
                    $lng ? (float)$lng : null,
                    $image,
                    $desc ?: null
                ]);
                db()->commit();

                session_regenerate_id(true);
                $_SESSION['user_id']  = $user_id;
                $_SESSION['username'] = $username;
                $_SESSION['role']     = 'provider';
                header('Location: ../dashboard.php');
                exit;
            } catch (Exception $e) {
                db()->rollBack();
                $error = 'حدث خطأ. يرجى المحاولة مجدداً.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($code) ?>" dir="<?= htmlspecialchars($dir) ?>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= htmlspecialchars(t('reg_provider')) ?> — <?= htmlspecialchars(t('site_name')) ?></title>
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🌴</text></svg>">
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="../css/style.css">
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
  <style>
    body { background: var(--cream); }
    .auth-card { animation: fadeUp .45s ease both; max-width: 520px; }
    @keyframes fadeUp { from { opacity:0; transform:translateY(24px); } to { opacity:1; transform:none; } }
    #map { width:100%; height:200px; border-radius: var(--r); }
    .map-container { margin-bottom: 14px; }
  </style>
</head>
<body>

<div class="auth-wrap">
  <div class="auth-card">

    <!-- Activity badge -->
    <div style="text-align:center;margin-bottom:16px">
      <span class="provider-badge"><?= $act_icons[$activityType] ?> <?= htmlspecialchars($act_labels[$activityType]) ?></span>
    </div>

    <h1 class="auth-title"><?= htmlspecialchars(t('reg_provider')) ?></h1>

    <?php if ($error): ?>
      <div class="error-box">⚠️ <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" novalidate>
      <input type="hidden" name="activity_type" value="<?= htmlspecialchars($activityType) ?>">

      <div class="form-group">
        <input type="text" name="biz_name" class="form-input"
               placeholder="<?= htmlspecialchars(t('biz_name')) ?>"
               value="<?= htmlspecialchars($_POST['biz_name'] ?? '') ?>" required>
      </div>
      <div class="form-group">
        <input type="text" name="username" class="form-input"
               placeholder="<?= htmlspecialchars(t('username')) ?>"
               value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required>
      </div>
      <div class="form-group">
        <input type="password" name="password" class="form-input"
               placeholder="<?= htmlspecialchars(t('password')) ?>" required>
      </div>
      <div class="form-group">
        <input type="password" name="confirm" class="form-input"
               placeholder="<?= htmlspecialchars(t('confirm_pass')) ?>" required>
      </div>
      <div class="form-group">
        <input type="email" name="email" class="form-input"
               placeholder="<?= htmlspecialchars(t('email')) ?>"
               value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
      </div>
      <div class="form-group">
        <input type="tel" name="phone" class="form-input"
               placeholder="<?= htmlspecialchars(t('phone')) ?>"
               value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>" required>
      </div>
      <div class="form-group">
        <input type="text" name="address" class="form-input"
               placeholder="<?= htmlspecialchars(t('address')) ?>"
               value="<?= htmlspecialchars($_POST['address'] ?? '') ?>">
      </div>
      <div class="form-group">
        <textarea name="description" class="form-input" rows="3"
                  placeholder="<?= htmlspecialchars(t('description')) ?>"
                  style="resize:vertical"><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>
      </div>

      <!-- Map -->
      <div class="map-container">
        <div id="map"></div>
        <p style="font-size:.78rem;color:var(--muted);margin-top:6px;text-align:center">📍 <?= htmlspecialchars(t('map_pin')) ?></p>
      </div>
      <input type="hidden" name="lat" id="latInput" value="<?= htmlspecialchars($_POST['lat'] ?? '') ?>">
      <input type="hidden" name="lng" id="lngInput" value="<?= htmlspecialchars($_POST['lng'] ?? '') ?>">

      <!-- Image upload -->
      <div class="upload-zone" id="uploadZone">
        <input type="file" name="image" id="imageInput" accept="image/*">
        <div id="uploadContent">
          <div style="font-size:1.8rem;margin-bottom:6px">📸</div>
          <p><?= htmlspecialchars(t('upload_img')) ?></p>
        </div>
      </div>

      <!-- Terms -->
      <div class="terms-wrap">
        <input type="checkbox" name="terms" id="terms" <?= isset($_POST['terms'])?'checked':'' ?>>
        <label for="terms" class="terms-text">
          <strong><?= htmlspecialchars(t('terms_agree')) ?></strong><br>
          <?= htmlspecialchars(t('terms_detail')) ?>
        </label>
      </div>

      <button type="submit" class="btn btn-green"><?= htmlspecialchars(t('save_register')) ?></button>
    </form>

    <div style="text-align:center;margin-top:14px">
      <a href="choose_activity.php<?= $code!=='ar'?'?lang='.$code:'' ?>" class="btn-ghost" style="font-size:.88rem;color:var(--muted);font-family:var(--font)">
        ← <?= htmlspecialchars(t('back')) ?>
      </a>
    </div>

  </div>
</div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
// El M'Ghair default center
var lat = parseFloat(document.getElementById('latInput').value) || 33.9536;
var lng = parseFloat(document.getElementById('lngInput').value) || 5.9256;

var map = L.map('map').setView([lat, lng], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap', maxZoom: 19
}).addTo(map);

var marker = L.marker([lat, lng], {draggable: true}).addTo(map);

function updateInputs(latlng) {
  document.getElementById('latInput').value = latlng.lat.toFixed(7);
  document.getElementById('lngInput').value = latlng.lng.toFixed(7);
}

if (document.getElementById('latInput').value) updateInputs({lat, lng});

marker.on('dragend', function(e) { updateInputs(e.target.getLatLng()); });
map.on('click', function(e) {
  marker.setLatLng(e.latlng);
  updateInputs(e.latlng);
});

// Image preview
document.getElementById('uploadZone').addEventListener('click', function() {
  document.getElementById('imageInput').click();
});
document.getElementById('imageInput').addEventListener('change', function() {
  var file = this.files[0];
  if (!file) return;
  var reader = new FileReader();
  reader.onload = function(e) {
    document.getElementById('uploadContent').innerHTML =
      '<img src="' + e.target.result + '" class="upload-preview"><p style="font-size:.78rem;color:var(--g-main);font-weight:700">' + file.name + '</p>';
  };
  reader.readAsDataURL(file);
});
</script>

</body>
</html>
