<?php
require '../config.php';
session_start();
require 'navbar.php';
if (!isset($_SESSION['user_id'])) {
  header("Location: login.php");
  exit;
}

$user_id = $_SESSION['user_id'];
$query = mysqli_query($conn, "SELECT * FROM pengguna WHERE id = $user_id");
$user = mysqli_fetch_assoc($query);

if ($user['peran'] !== 'pelanggan') {
  echo "Akses ditolak!";
  exit;
}
?>

<!DOCTYPE html>
<html>

<head>
  <title>Profil Saya</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <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-fluid {
      padding-left: 15px;
      padding-right: 15px;
    }

    .profile-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;
      max-width: 800px;
      margin-left: auto;
      margin-right: auto;
    }

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

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

    .form-control {
      border: 1px solid #ccc;
      padding: 12px;
      border-radius: 4px;
      color: #333;
      background-color: #fff;
      font-size: 1rem;
      width: 100%;
    }

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

    .btn {
      padding: 12px 24px;
      border-radius: 4px;
      cursor: pointer;
      font-weight: bold;
      transition: all 0.3s ease;
      font-size: 1rem;
      width: 100%;
      margin-bottom: 10px;
    }

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

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

    .btn-warning {
      background-color: #f0f0f0;
      color: #333;
      border: 1px solid #ccc;
    }

    .btn-warning:hover {
      background-color: #e0e0e0;
      border-color: #bbb;
    }

    .btn-secondary {
      background-color: #ccc;
      color: #333;
      border: 1px solid #ccc;
    }

    .btn-secondary:hover {
      background-color: #bbb;
      border-color: #aaa;
    }

    .modal-content {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
    }

    .modal-header {
      border-bottom: 1px solid #eee;
    }

    .modal-title {
      color: #222;
    }

    .modal-footer {
      border-top: 1px solid #eee;
    }

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

    .is-invalid:focus {
      border-color: #dc3545 !important;
      box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25) !important;
    }

    /* Desktop styles */
    @media (min-width: 768px) {
      .profile-container {
        padding: 40px;
        margin-top: 50px;
        margin-bottom: 50px;
      }

      .btn {
        width: auto;
        margin-right: 10px;
        margin-bottom: 0;
      }

      .btn-warning {
        margin-left: 10px;
        margin-right: 0;
      }


    }

    /* Tablet styles */
    @media (max-width: 991.98px) and (min-width: 768px) {
      .profile-container {
        max-width: 90%;
        padding: 30px;
      }

      h2 {
        font-size: 1.6rem;
      }
    }

    /* Mobile styles - maintaining desktop layout but scaled */
    @media (max-width: 767.98px) {
      body {
        background-color: #f8f8f8;
      }

      .container-fluid {
        padding-left: 10px;
        padding-right: 10px;
      }

      .profile-container {
        margin-top: 20px;
        margin-bottom: 20px;
        padding: 20px;
        max-width: 100%;
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      }

      h2 {
        font-size: 1.4rem;
        padding-bottom: 10px;
        margin-bottom: 20px;
      }

      label {
        font-size: 0.9rem;
        margin-bottom: 4px;
      }

      .form-control {
        padding: 10px;
        font-size: 0.95rem;
        margin-bottom: 15px;
      }

      .btn {
        padding: 10px 20px;
        font-size: 0.95rem;
        margin-bottom: 8px;
      }

      /* Keep 2-column layout on mobile for better space usage */
      .row .col-md-6 {
        padding-left: 5px;
        padding-right: 5px;
      }

      /* Full width for address field */
      .col-12 .form-control {
        margin-bottom: 20px;
      }

      /* Modal adjustments for mobile */
      .modal-dialog {
        margin: 10px;
      }

      .modal-content {
        border-radius: 8px;
      }

      .modal-header .modal-title {
        font-size: 1.1rem;
      }

      .modal-body {
        padding: 15px;
      }

      .modal-footer {
        padding: 10px 15px;
      }

      .modal-footer .btn {
        width: 100%;
        margin-bottom: 5px;
      }
    }

    /* Extra small mobile devices */
    @media (max-width: 575.98px) {
      .profile-container {
        padding: 15px;
        margin-top: 15px;
        margin-bottom: 15px;
      }

      h2 {
        font-size: 1.3rem;
      }

      .form-control {
        width: 95%;
        padding: 8px;
        font-size: 0.9rem;
        margin: 0 auto;
      }

      .btn {
        padding: 8px 16px;
        font-size: 0.9rem;
      }

      /* Stack columns on very small screens */
      .row .col-md-6 {
        flex: 0 0 100%;
        max-width: 100%;
        padding-left: 0;
        padding-right: 0;
        margin-bottom: 5px;
      }

      label {
        margin-left: 10px;
      }
    }

    /* Ensure proper spacing */
    .mb-3 {
      margin-bottom: 1rem !important;
    }

    @media (max-width: 767.98px) {
      .mb-3 {
        margin-bottom: 0.8rem !important;
      }
    }
  </style>
</head>

<body>
  <div class="container-fluid">
    <div class="profile-container">
      <form action="../proses/proses_update_profile.php" method="POST" id="profileForm">
        <div class="row">
          <div class="col-md-6 mb-3">
            <label>Nama Lengkap</label>
            <input type="text" name="nama" value="<?= htmlspecialchars($user['nama'] ?? '') ?>" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Email</label>
            <input type="email" name="email" value="<?= htmlspecialchars($user['email'] ?? '') ?>" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Jenis Kelamin</label>
            <select name="jenis_kelamin" class="form-control" required>
              <option value="">Pilih Jenis Kelamin</option>
              <option value="L" <?= ($user['jenis_kelamin'] ?? '') == 'L' ? 'selected' : '' ?>>Laki-laki</option>
              <option value="P" <?= ($user['jenis_kelamin'] ?? '') == 'P' ? 'selected' : '' ?>>Perempuan</option>
            </select>
          </div>
          <div class="col-md-6 mb-3">
            <label>No Telepon</label>
            <input type="text" name="no_telp" value="<?= htmlspecialchars($user['no_telp'] ?? '') ?>" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Provinsi</label>
            <select name="provinsi" id="provinsi" class="form-control" required>
              <option value="">Loading...</option>
            </select>
          </div>
          <div class="col-md-6 mb-3">
            <label>Kabupaten/Kota</label>
            <select name="kabupaten" id="kabupaten" class="form-control" 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-control" 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-control" required>
              <option value="">Pilih Kecamatan dulu</option>
            </select>
          </div>
          <div class="col-12 mb-3">
            <label class="ms-0">Alamat Lengkap</label>
            <textarea name="alamat_lengkap" class="form-control m-0 w-100" rows="3" placeholder="Contoh: Jl. Sudirman No. 123, RT 01/RW 05"><?= htmlspecialchars($user['alamat_lengkap'] ?? '') ?></textarea>
          </div>
          <div class="col-12">
            <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
            <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#modalUbahPassword">Ubah Password</button>
          </div>
        </div>
      </form>

      <div class="modal fade" id="modalUbahPassword" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
          <form method="POST" action="../proses/proses_ubah_password.php" class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">Ubah Password</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
              <div class="mb-3">
                <label>Password Lama</label>
                <input type="password" name="password_lama" class="form-control" required>
              </div>
              <div class="mb-3">
                <label>Password Baru</label>
                <input type="password" name="password_baru" class="form-control" required>
              </div>
              <div class="mb-3">
                <label>Konfirmasi Password Baru</label>
                <input type="password" name="konfirmasi_password_baru" class="form-control" required>
              </div>
            </div>
            <div class="modal-footer">
              <button type="submit" class="btn btn-primary">Simpan</button>
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
  <?php include '../footer.php'; ?>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">

  <script>
    $(document).ready(function() {
      const currentProvinsi = "<?= htmlspecialchars($user['provinsi'] ?? '') ?>";
      const currentKabupaten = "<?= htmlspecialchars($user['kabupaten_kota'] ?? '') ?>";
      const currentKecamatan = "<?= htmlspecialchars($user['kecamatan'] ?? '') ?>";
      const currentKelurahan = "<?= htmlspecialchars($user['kelurahan'] ?? '') ?>";

      // Load provinces on page load
      loadProvinces();

      function loadProvinces() {
        $.ajax({
          url: 'https://www.emsifa.com/api-wilayah-indonesia/api/provinces.json',
          type: 'GET',
          success: function(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) {
                loadKabupaten(selectedOption.data('id'));
              }
            }
          },
          error: function() {
            $('#provinsi').html('<option value="">Error loading provinsi</option>');
          }
        });
      }

      function loadKabupaten(provinceId) {
        $.ajax({
          url: `https://www.emsifa.com/api-wilayah-indonesia/api/regencies/${provinceId}.json`,
          type: 'GET',
          success: function(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) {
                loadKecamatan(selectedOption.data('id'));
              }
            }
          },
          error: function() {
            $('#kabupaten').html('<option value="">Error loading kabupaten</option>');
          }
        });
      }

      function loadKecamatan(regencyId) {
        $.ajax({
          url: `https://www.emsifa.com/api-wilayah-indonesia/api/districts/${regencyId}.json`,
          type: 'GET',
          success: function(data) {
            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) {
                loadKelurahan(selectedOption.data('id'));
              }
            }
          },
          error: function() {
            $('#kecamatan').html('<option value="">Error loading kecamatan</option>');
          }
        });
      }

      function loadKelurahan(districtId) {
        $.ajax({
          url: `https://www.emsifa.com/api-wilayah-indonesia/api/villages/${districtId}.json`,
          type: 'GET',
          success: function(data) {
            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() {
            $('#kelurahan').html('<option value="">Error loading kelurahan</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);
        }
      });

      // Form validation with specific field names
      $('#profileForm').submit(function(e) {
        const requiredFields = [{
            name: 'nama',
            label: 'Nama Lengkap'
          },
          {
            name: 'email',
            label: 'Email'
          },
          {
            name: 'jenis_kelamin',
            label: 'Jenis Kelamin'
          },
          {
            name: 'provinsi',
            label: 'Provinsi'
          },
          {
            name: 'kabupaten',
            label: 'Kabupaten/Kota'
          },
          {
            name: 'kecamatan',
            label: 'Kecamatan'
          },
          {
            name: 'kelurahan',
            label: 'Kelurahan'
          }
        ];

        let isValid = true;
        let missingFields = [];

        requiredFields.forEach(function(field) {
          const value = $(`[name="${field.name}"]`).val();
          if (!value || value.trim() === '') {
            isValid = false;
            missingFields.push(field.label);
            $(`[name="${field.name}"]`).addClass('is-invalid');
          } else {
            $(`[name="${field.name}"]`).removeClass('is-invalid');
          }
        });

        if (!isValid) {
          e.preventDefault();
          alert('Field berikut harus diisi: ' + missingFields.join(', '));
        }
      });

      // Remove invalid class on input change
      $('input, select, textarea').on('change input', function() {
        $(this).removeClass('is-invalid');
      });
    });
  </script>
</body>

</html>