<?php
require '../config.php';
session_start();
require 'navbar.php';

if (!isset($_SESSION['user_id'])) {
  header("Location: ../login.php");
  exit;
}

$user_id = $_SESSION['user_id'];

// Ambil data pengguna
$query = "SELECT * FROM pengguna WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$pengguna = $result->fetch_assoc();

$notif = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $alamat = $_POST['alamat_lengkap'] ?? '';
  $no_telp = $_POST['no_telp'] ?? '';
  $kelurahan = $_POST['kelurahan'] ?? '';
  $kecamatan = $_POST['kecamatan'] ?? '';
  $kabupaten_kota = $_POST['kabupaten_kota'] ?? '';
  $provinsi = $_POST['provinsi'] ?? '';

  // Validasi input
  if (empty($alamat) || empty($no_telp) || empty($kelurahan) || empty($kecamatan) || empty($kabupaten_kota) || empty($provinsi)) {
    $notif = '<div class="alert alert-danger mt-3">Semua field harus diisi!</div>';
  } else {
    $update_query = "UPDATE pengguna SET alamat_lengkap = ?, no_telp = ?, kelurahan = ?, kecamatan = ?, kabupaten_kota = ?, provinsi = ? WHERE id = ?";
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param("ssssssi", $alamat, $no_telp, $kelurahan, $kecamatan, $kabupaten_kota, $provinsi, $user_id);

    if ($update_stmt->execute()) {
      $notif = '<div class="alert alert-success mt-3">Alamat dan nomor telepon berhasil disimpan!</div>';
      // Refresh data
      $stmt->execute();
      $result = $stmt->get_result();
      $pengguna = $result->fetch_assoc();
    } else {
      $notif = '<div class="alert alert-danger mt-3">Gagal menyimpan data. Silakan coba lagi.</div>';
    }
  }
}
?>
<!DOCTYPE html>
<html lang="id">

<head>
  <meta charset="UTF-8">
  <title>Alamat Saya</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      background-color: #f8f8f8;
      color: #333;
      font-family: Arial, sans-serif;
    }

    .container {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      padding: 30px;
      margin-top: 40px;
      margin-bottom: 40px;
    }

    h2 {
      color: #222;
      border-bottom: 1px solid #eee;
      padding-bottom: 15px;
      margin-bottom: 30px;
    }

    label {
      color: #555;
      font-weight: bold;
      margin-bottom: 5px;
      display: block;
    }

    .form-control {
      border: 1px solid #ccc;
      padding: 10px;
      border-radius: 4px;
      color: #333;
      background-color: #fff;
    }

    .form-control:focus,
    .form-select:focus {
      border-color: #888;
      box-shadow: 0 0 0 0.2rem rgba(0, 0, 0, 0.1);
      outline: none;
    }

    .form-select {
      border: 1px solid #ccc;
      padding: 10px;
      border-radius: 4px;
      color: #333;
      background-color: #fff;
    }

    .is-invalid {
      border-color: #dc3545 !important;
    }

    .loading-select {
      background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"><circle cx="6" cy="6" r="1"><animate attributeName="r" begin="0s" dur="1s" values="1;2;1" calcMode="linear" repeatCount="indefinite"/></circle></svg>');
      background-repeat: no-repeat;
      background-position: right 10px center;
      background-size: 16px;
    }

    .success-msg {
      color: #28a745;
      font-weight: bold;
    }

    .error-msg {
      color: #dc3545;
      font-weight: bold;
    }

    .btn {
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      font-weight: bold;
      transition: all 0.3s ease;
    }

    .btn-primary {
      background-color: #333;
      color: #fff;
      border: 1px solid #333;
    }

    .btn-primary:hover {
      background-color: #555;
      border-color: #555;
    }

    .btn-secondary {
      background-color: #6c757d;
      color: #fff;
      border: 1px solid #6c757d;
      text-decoration: none;
    }

    .btn-secondary:hover {
      background-color: #5a6268;
      border-color: #545b62;
      color: #fff;
    }

    @media (max-width: 768px) {
      .container {
        padding: 15px;
        margin-top: 20px;
        margin-bottom: 20px;
      }

      .btn {
        width: 100%;
        margin-bottom: 10px;
      }
    }
  </style>
</head>

<body>
  <div class="container py-5">
    <h2>Alamat & Nomor Telepon</h2>
    <?= $notif ?>
    <form method="POST">
      <div class="row">
        <div class="col-12 mb-3">
          <label>Alamat Lengkap</label>
          <textarea name="alamat_lengkap" class="form-control" rows="3" required placeholder="Contoh: Jl. Sudirman No. 123, RT 01/RW 02"><?= htmlspecialchars($pengguna['alamat_lengkap'] ?? '') ?></textarea>
        </div>
        <div class="col-md-6 mb-3">
          <label>No. Telepon</label>
          <input type="text" name="no_telp" class="form-control" value="<?= htmlspecialchars($pengguna['no_telp'] ?? '') ?>" required placeholder="08xxxxxxxxxx">
        </div>
        <div class="col-md-6 mb-3">
          <label>Provinsi</label>
          <select name="provinsi" id="provinsi" class="form-select" required>
            <option value="">Loading...</option>
          </select>
        </div>
        <div class="col-md-6 mb-3">
          <label>Kabupaten/Kota</label>
          <select name="kabupaten_kota" id="kabupaten" class="form-select" required>
            <option value="">Pilih Provinsi dulu</option>
          </select>
        </div>
        <div class="col-md-6 mb-3">
          <label>Kecamatan</label>
          <select name="kecamatan" id="kecamatan" class="form-select" required>
            <option value="">Pilih Kabupaten dulu</option>
          </select>
        </div>
        <div class="col-md-6 mb-3">
          <label>Kelurahan</label>
          <select name="kelurahan" id="kelurahan" class="form-select" required>
            <option value="">Pilih Kecamatan dulu</option>
          </select>
        </div>
        <div class="col-12">
          <button type="submit" class="btn btn-primary">Simpan Alamat</button>
          <a href="profile.php" class="btn btn-secondary ms-2">Kembali ke Profil</a>
        </div>
      </div>
    </form>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    $(document).ready(function() {
      const currentProvinsi = "<?= htmlspecialchars($pengguna['provinsi'] ?? '') ?>";
      const currentKabupaten = "<?= htmlspecialchars($pengguna['kabupaten_kota'] ?? '') ?>";
      const currentKecamatan = "<?= htmlspecialchars($pengguna['kecamatan'] ?? '') ?>";
      const currentKelurahan = "<?= htmlspecialchars($pengguna['kelurahan'] ?? '') ?>";

      console.log('Current address data:', {
        provinsi: currentProvinsi,
        kabupaten: currentKabupaten,
        kecamatan: currentKecamatan,
        kelurahan: currentKelurahan
      });

      // Load provinces on page load
      loadProvinces();

      function loadProvinces() {
        $('#provinsi').html('<option value="">Loading provinsi...</option>');

        // Try local API first, then fallback to external API
        $.ajax({
          url: '../api/wilayah.php?type=provinces',
          type: 'GET',
          timeout: 5000,
          success: function(response) {
            if (response.success) {
              console.log('Provinces loaded from local API:', response.data.length);
              populateProvinces(response.data);
            } else {
              throw new Error(response.error);
            }
          },
          error: function() {
            console.log('Local API failed, trying external API...');
            // Fallback to external API
            $.ajax({
              url: 'https://www.emsifa.com/api-wilayah-indonesia/api/provinces.json',
              type: 'GET',
              timeout: 10000,
              success: function(data) {
                console.log('Provinces loaded from external API:', data.length);
                populateProvinces(data);
              },
              error: function(xhr, status, error) {
                console.error('All APIs failed for provinces:', status, error);
                $('#provinsi').html('<option value="">Error loading provinces. Please refresh.</option>');
              }
            });
          }
        });
      }

      function populateProvinces(data) {
        let options = '<option value="">Pilih Provinsi</option>';
        data.forEach(function(provinsi) {
          const selected = currentProvinsi === provinsi.name ? 'selected' : '';
          options += `<option value="${provinsi.name}" data-id="${provinsi.id}" ${selected}>${provinsi.name}</option>`;
        });
        $('#provinsi').html(options);

        // If there's a current province, load its kabupaten
        if (currentProvinsi) {
          const selectedOption = $('#provinsi option:selected');
          if (selectedOption.length > 0) {
            const provinceId = selectedOption.data('id');
            console.log('Auto-loading kabupaten for province ID:', provinceId);
            loadKabupaten(provinceId);
          }
        }
      }

      function loadKabupaten(provinceId) {
        if (!provinceId) {
          console.error('Province ID is missing');
          return;
        }

        $('#kabupaten').html('<option value="">Loading kabupaten...</option>');
        console.log('Loading kabupaten for province ID:', provinceId);

        // Try local API first
        $.ajax({
          url: `../api/wilayah.php?type=regencies&id=${provinceId}`,
          type: 'GET',
          timeout: 5000,
          success: function(response) {
            if (response.success) {
              console.log('Kabupaten loaded from local API:', response.data.length);
              populateKabupaten(response.data);
            } else {
              throw new Error(response.error);
            }
          },
          error: function() {
            console.log('Local API failed, trying external API...');
            // Fallback to external API
            $.ajax({
              url: `https://www.emsifa.com/api-wilayah-indonesia/api/regencies/${provinceId}.json`,
              type: 'GET',
              timeout: 10000,
              success: function(data) {
                console.log('Kabupaten loaded from external API:', data.length);
                populateKabupaten(data);
              },
              error: function(xhr, status, error) {
                console.error('All APIs failed for kabupaten:', status, error, xhr.responseText);
                $('#kabupaten').html('<option value="">Error loading kabupaten. Please try again.</option>');
              }
            });
          }
        });
      }

      function populateKabupaten(data) {
        let options = '<option value="">Pilih Kabupaten/Kota</option>';
        data.forEach(function(kabupaten) {
          const selected = currentKabupaten === kabupaten.name ? 'selected' : '';
          options += `<option value="${kabupaten.name}" data-id="${kabupaten.id}" ${selected}>${kabupaten.name}</option>`;
        });
        $('#kabupaten').html(options);

        // If there's a current kabupaten, load its kecamatan
        if (currentKabupaten) {
          const selectedOption = $('#kabupaten option:selected');
          if (selectedOption.length > 0) {
            const regencyId = selectedOption.data('id');
            console.log('Auto-loading kecamatan for regency ID:', regencyId);
            loadKecamatan(regencyId);
          }
        }
      }

      function loadKecamatan(regencyId) {
        if (!regencyId) {
          console.error('Regency ID is missing');
          return;
        }

        $('#kecamatan').html('<option value="">Loading kecamatan...</option>');
        console.log('Loading kecamatan for regency ID:', regencyId);

        $.ajax({
          url: `https://www.emsifa.com/api-wilayah-indonesia/api/districts/${regencyId}.json`,
          type: 'GET',
          timeout: 10000,
          success: function(data) {
            console.log('Kecamatan loaded:', data.length);
            let options = '<option value="">Pilih Kecamatan</option>';
            data.forEach(function(kecamatan) {
              const selected = currentKecamatan === kecamatan.name ? 'selected' : '';
              options += `<option value="${kecamatan.name}" data-id="${kecamatan.id}" ${selected}>${kecamatan.name}</option>`;
            });
            $('#kecamatan').html(options);

            // If there's a current kecamatan, load its kelurahan
            if (currentKecamatan) {
              const selectedOption = $('#kecamatan option:selected');
              if (selectedOption.length > 0) {
                const districtId = selectedOption.data('id');
                console.log('Auto-loading kelurahan for district ID:', districtId);
                loadKelurahan(districtId);
              }
            }
          },
          error: function(xhr, status, error) {
            console.error('Error loading kecamatan:', status, error, xhr.responseText);
            $('#kecamatan').html('<option value="">Error loading kecamatan. Please try again.</option>');
          }
        });
      }

      function loadKelurahan(districtId) {
        if (!districtId) {
          console.error('District ID is missing');
          return;
        }

        $('#kelurahan').html('<option value="">Loading kelurahan...</option>');
        console.log('Loading kelurahan for district ID:', districtId);

        $.ajax({
          url: `https://www.emsifa.com/api-wilayah-indonesia/api/villages/${districtId}.json`,
          type: 'GET',
          timeout: 10000,
          success: function(data) {
            console.log('Kelurahan loaded:', data.length);
            let options = '<option value="">Pilih Kelurahan</option>';
            data.forEach(function(kelurahan) {
              const selected = currentKelurahan === kelurahan.name ? 'selected' : '';
              options += `<option value="${kelurahan.name}" data-id="${kelurahan.id}" ${selected}>${kelurahan.name}</option>`;
            });
            $('#kelurahan').html(options);
          },
          error: function(xhr, status, error) {
            console.error('Error loading kelurahan:', status, error, xhr.responseText);
            $('#kelurahan').html('<option value="">Error loading kelurahan. Please try again.</option>');
          }
        });
      }

      // Event handlers for cascading dropdowns
      $('#provinsi').change(function() {
        const selectedOption = $(this).find('option:selected');
        const provinceId = selectedOption.data('id');

        // Reset dependent dropdowns
        $('#kabupaten').html('<option value="">Pilih Kabupaten/Kota</option>');
        $('#kecamatan').html('<option value="">Pilih Kecamatan</option>');
        $('#kelurahan').html('<option value="">Pilih Kelurahan</option>');

        if (provinceId) {
          loadKabupaten(provinceId);
        }
      });

      $('#kabupaten').change(function() {
        const selectedOption = $(this).find('option:selected');
        const regencyId = selectedOption.data('id');

        // Reset dependent dropdowns
        $('#kecamatan').html('<option value="">Pilih Kecamatan</option>');
        $('#kelurahan').html('<option value="">Pilih Kelurahan</option>');

        if (regencyId) {
          loadKecamatan(regencyId);
        }
      });

      $('#kecamatan').change(function() {
        const selectedOption = $(this).find('option:selected');
        const districtId = selectedOption.data('id');

        // Reset dependent dropdown
        $('#kelurahan').html('<option value="">Pilih Kelurahan</option>');

        if (districtId) {
          loadKelurahan(districtId);
        }
      });
    });
  </script>

  <?php include '../footer.php'; ?>
</body>

</html>