-- ============================================================
--  WebGIS Pengentasan Kemiskinan
--  Database: webgis_uas
--  Versi: 2.0 (Full System)
-- ============================================================

CREATE DATABASE IF NOT EXISTS webgis_uas
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE webgis_uas;

-- ============================================================
-- 1. ROLE (hak akses)
-- ============================================================
CREATE TABLE role (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  nama       VARCHAR(50)  NOT NULL,          -- masyarakat | pengurus | pimpinan | admin
  deskripsi  TEXT
) ENGINE=InnoDB;

-- ============================================================
-- 2. USER (login)
-- ============================================================
CREATE TABLE user (
  id          INT AUTO_INCREMENT PRIMARY KEY,
  username    VARCHAR(80)  NOT NULL UNIQUE,
  password    VARCHAR(255) NOT NULL,          -- bcrypt
  nama_lengkap VARCHAR(120),
  email       VARCHAR(120),
  role_id     INT          NOT NULL,
  aktif       TINYINT(1)   DEFAULT 1,
  created_at  DATETIME     DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (role_id) REFERENCES role(id)
) ENGINE=InnoDB;

-- ============================================================
-- 3. RUMAH IBADAH
-- ============================================================
CREATE TABLE rumah_ibadah (
  id       INT AUTO_INCREMENT PRIMARY KEY,
  nama     VARCHAR(150) NOT NULL,
  jenis    ENUM('masjid','gereja','pura','vihara','klenteng','lainnya') NOT NULL,
  kontak   VARCHAR(50),
  alamat   TEXT,
  lat      DOUBLE NOT NULL,
  lng      DOUBLE NOT NULL,
  radius   DOUBLE DEFAULT 500,               -- meter, zona layanan
  user_id  INT,                              -- pengurus penanggung-jawab
  FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ============================================================
-- 4. KELUARGA (Kartu Keluarga)
-- ============================================================
CREATE TABLE keluarga (
  id              INT AUTO_INCREMENT PRIMARY KEY,
  no_kk           VARCHAR(20) UNIQUE NOT NULL,
  alamat          TEXT,
  lat             DOUBLE,
  lng             DOUBLE,
  rumah_ibadah_id INT,
  created_at      DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at      DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (rumah_ibadah_id) REFERENCES rumah_ibadah(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ============================================================
-- 5. PENDUDUK
-- ============================================================
CREATE TABLE penduduk (
  id                INT AUTO_INCREMENT PRIMARY KEY,
  nik               VARCHAR(16) UNIQUE NOT NULL,
  nama              VARCHAR(150) NOT NULL,
  jenis_kelamin     ENUM('L','P') NOT NULL,
  tanggal_lahir     DATE,
  -- umur dihitung via VIEW / fungsi, tidak disimpan statis
  status_keluarga   ENUM('kepala_keluarga','istri','anak','orang_tua','lainnya') DEFAULT 'lainnya',
  status_perkawinan ENUM('belum_kawin','kawin','cerai_hidup','cerai_mati') DEFAULT 'belum_kawin',
  status_hidup      ENUM('hidup','meninggal') DEFAULT 'hidup',
  alamat            TEXT,
  lat               DOUBLE,
  lng               DOUBLE,
  no_hp             VARCHAR(20),
  pekerjaan         VARCHAR(100),
  penghasilan       DECIMAL(15,2) DEFAULT 0,
  status_ekonomi    ENUM('miskin','rentan','mampu') DEFAULT 'rentan',
  -- pendidikan
  pendidikan_terakhir ENUM('tidak_sekolah','sd','smp','sma','d1','d2','d3','s1','s2','s3') DEFAULT 'tidak_sekolah',
  status_pendidikan   ENUM('sekolah','tidak_sekolah','lulus','putus_sekolah') DEFAULT 'tidak_sekolah',
  -- relasi
  keluarga_id       INT,
  rumah_ibadah_id   INT,
  -- meta
  created_at        DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at        DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (keluarga_id)     REFERENCES keluarga(id) ON DELETE SET NULL,
  FOREIGN KEY (rumah_ibadah_id) REFERENCES rumah_ibadah(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ============================================================
-- 6. RIWAYAT PELATIHAN
-- ============================================================
CREATE TABLE pelatihan (
  id          INT AUTO_INCREMENT PRIMARY KEY,
  penduduk_id INT NOT NULL,
  nama_pelatihan VARCHAR(150),
  penyelenggara  VARCHAR(100),
  tanggal        DATE,
  sertifikat     TINYINT(1) DEFAULT 0,
  FOREIGN KEY (penduduk_id) REFERENCES penduduk(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- ============================================================
-- 7. JENIS BANTUAN (master)
-- ============================================================
CREATE TABLE jenis_bantuan (
  id       INT AUTO_INCREMENT PRIMARY KEY,
  nama     VARCHAR(100) NOT NULL,            -- sembako, pendidikan, kesehatan, …
  kategori ENUM('sembako','pendidikan','kesehatan','ekonomi','lainnya') DEFAULT 'lainnya',
  satuan   VARCHAR(50),                      -- karung, paket, rupiah, …
  deskripsi TEXT
) ENGINE=InnoDB;

-- ============================================================
-- 8. HISTORI BANTUAN
-- ============================================================
CREATE TABLE histori_bantuan (
  id              INT AUTO_INCREMENT PRIMARY KEY,
  penduduk_id     INT NOT NULL,
  jenis_bantuan_id INT NOT NULL,
  sumber_bantuan  VARCHAR(100),              -- rumah ibadah / pemerintah / donatur
  tanggal         DATE NOT NULL,
  jumlah          DECIMAL(10,2),
  status          ENUM('direncanakan','disalurkan','selesai') DEFAULT 'direncanakan',
  catatan         TEXT,
  user_id         INT,                       -- yg menginput
  FOREIGN KEY (penduduk_id)      REFERENCES penduduk(id) ON DELETE CASCADE,
  FOREIGN KEY (jenis_bantuan_id) REFERENCES jenis_bantuan(id),
  FOREIGN KEY (user_id)          REFERENCES user(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ============================================================
-- 9. LAPORAN MASYARAKAT
-- ============================================================
CREATE TABLE laporan (
  id           INT AUTO_INCREMENT PRIMARY KEY,
  nama_pelapor VARCHAR(100),
  penduduk_id  INT,                          -- opsional, terkait siapa
  deskripsi    TEXT NOT NULL,
  lat          DOUBLE,
  lng          DOUBLE,
  foto         VARCHAR(255),
  urgensi      ENUM('rendah','sedang','tinggi','darurat') DEFAULT 'sedang',
  status       ENUM('pending','diverifikasi','diproses','selesai') DEFAULT 'pending',
  ditangani_oleh INT,
  created_at   DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at   DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (penduduk_id)     REFERENCES penduduk(id) ON DELETE SET NULL,
  FOREIGN KEY (ditangani_oleh)  REFERENCES user(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ============================================================
-- 10. CHAT / KOMUNIKASI ANTAR PENGURUS
-- ============================================================
CREATE TABLE chat (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  from_user  INT NOT NULL,
  to_user    INT,                            -- NULL = broadcast ke semua pengurus
  pesan      TEXT NOT NULL,
  dibaca     TINYINT(1) DEFAULT 0,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (from_user) REFERENCES user(id) ON DELETE CASCADE,
  FOREIGN KEY (to_user)   REFERENCES user(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ============================================================
-- 11. LOG AKTIVITAS
-- ============================================================
CREATE TABLE log_aktivitas (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  user_id    INT,
  aksi       VARCHAR(100),                   -- create_penduduk, update_bantuan, …
  tabel      VARCHAR(50),
  record_id  INT,
  detail     TEXT,
  ip         VARCHAR(45),
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ============================================================
-- VIEW: umur otomatis
-- ============================================================
CREATE OR REPLACE VIEW v_penduduk AS
SELECT
  p.*,
  TIMESTAMPDIFF(YEAR, p.tanggal_lahir, CURDATE()) AS umur,
  k.no_kk,
  r.nama  AS nama_ibadah,
  r.jenis AS jenis_ibadah
FROM penduduk p
LEFT JOIN keluarga     k ON p.keluarga_id     = k.id
LEFT JOIN rumah_ibadah r ON p.rumah_ibadah_id = r.id;

-- ============================================================
-- DATA AWAL: ROLE
-- ============================================================
INSERT INTO role (nama, deskripsi) VALUES
  ('admin',     'Administrator sistem penuh'),
  ('pengurus',  'Pengurus Rumah Ibadah – input & verifikasi'),
  ('pimpinan',  'Pimpinan Daerah – read-only & dashboard'),
  ('masyarakat','Warga biasa – lapor & lihat data terbatas');

-- ============================================================
-- DATA AWAL: USER ([REDACTED]→ bcrypt)
-- ============================================================
INSERT INTO user (username, password, nama_lengkap, email, role_id) VALUES
  ('admin',     '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Administrator',        'admin@webgis.id',    1),
  ('pengurus1', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Ahmad Fauzi',          'ahmad@masjid.id',    2),
  ('pengurus2', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Budi Santoso',         'budi@gereja.id',     2),
  ('pimpinan1', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Camat Pontianak Kota', 'camat@pontianak.id', 3),
  ('warga1',    '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Dewi Lestari',         'dewi@gmail.com',     4);

-- ============================================================
-- DATA AWAL: RUMAH IBADAH (Pontianak area)
-- ============================================================
INSERT INTO rumah_ibadah (nama, jenis, kontak, alamat, lat, lng, radius, user_id) VALUES
  ('Masjid Raya Mujahidin',    'masjid',  '0561-7001234', 'Jl. Ahmad Yani, Pontianak',     -0.0231,  109.3294, 600, 2),
  ('Masjid Al-Falah',          'masjid',  '0561-7005678', 'Jl. Gajah Mada, Pontianak',     -0.0312,  109.3215, 500, 2),
  ('Gereja Katolik Katedral',  'gereja',  '0561-7009012', 'Jl. Rahadi Usman, Pontianak',   -0.0280,  109.3320, 550, 3),
  ('Vihara Bodhicitta Maitreya','vihara', '0561-7003456', 'Jl. Diponegoro, Pontianak',     -0.0265,  109.3341, 400, NULL),
  ('Gereja GPIB Imanuel',      'gereja',  '0561-7007890', 'Jl. Tanjungpura, Pontianak',    -0.0245,  109.3270, 500, 3);

-- ============================================================
-- DATA AWAL: KELUARGA
-- ============================================================
INSERT INTO keluarga (no_kk, alamat, lat, lng, rumah_ibadah_id) VALUES
  ('6171010101230001', 'Jl. Veteran No.12, RT01 RW01',   -0.0250, 109.3280, 1),
  ('6171010101230002', 'Jl. Tanjungpura No.45, RT02 RW01',-0.0270, 109.3310, 3),
  ('6171010101230003', 'Jl. Gajah Mada No.7, RT01 RW02', -0.0235, 109.3225, 2),
  ('6171010101230004', 'Jl. Diponegoro No.33, RT03 RW02',-0.0280, 109.3355, 4),
  ('6171010101230005', 'Jl. Ahmad Yani No.88, RT02 RW03',-0.0195, 109.3290, 1);

-- ============================================================
-- DATA AWAL: PENDUDUK (dummy realistis)
-- ============================================================
INSERT INTO penduduk
  (nik, nama, jenis_kelamin, tanggal_lahir, status_keluarga, status_perkawinan,
   status_hidup, alamat, lat, lng, no_hp, pekerjaan, penghasilan,
   status_ekonomi, pendidikan_terakhir, status_pendidikan, keluarga_id, rumah_ibadah_id)
VALUES
  ('6171010101800001','Hasan Basri',      'L','1980-05-15','kepala_keluarga','kawin',       'hidup','Jl. Veteran No.12',   -0.02510,109.32810,'081234560001','buruh_harian',  800000, 'miskin', 'sd',  'tidak_sekolah',1,1),
  ('6171010101820002','Siti Rahmawati',   'P','1982-08-22','istri',          'kawin',       'hidup','Jl. Veteran No.12',   -0.02510,109.32810,'081234560002','ibu_rumah_tangga',0,    'miskin', 'sd',  'tidak_sekolah',1,1),
  ('6171010101070003','Rizky Pratama',    'L','2007-03-10','anak',           'belum_kawin', 'hidup','Jl. Veteran No.12',   -0.02520,109.32820,'',           'pelajar',       0,      'miskin', 'smp', 'sekolah',      1,1),
  ('6171010101750004','Widodo Santoso',   'L','1975-11-30','kepala_keluarga','kawin',       'hidup','Jl. Tanjungpura No.45',-0.02700,109.33100,'081234560004','pedagang',      1500000,'rentan', 'sma', 'lulus',        2,3),
  ('6171010101780005','Maria Goretti',    'P','1978-06-18','istri',          'kawin',       'hidup','Jl. Tanjungpura No.45',-0.02700,109.33100,'081234560005','penjahit',      700000, 'rentan', 'smp', 'lulus',        2,3),
  ('6171010101090006','Anastasia Dewi',   'P','2009-01-25','anak',           'belum_kawin', 'hidup','Jl. Tanjungpura No.45',-0.02710,109.33110,'',           'pelajar',       0,      'rentan', 'sd',  'sekolah',      2,3),
  ('6171010101650007','Darman Husin',     'L','1965-04-04','kepala_keluarga','kawin',       'hidup','Jl. Gajah Mada No.7', -0.02355,109.32260,'081234560007','nelayan',       600000, 'miskin', 'sd',  'tidak_sekolah',3,2),
  ('6171010101680008','Aminah Binti Umar','P','1968-09-12','istri',          'kawin',       'hidup','Jl. Gajah Mada No.7', -0.02355,109.32260,'081234560008','ibu_rumah_tangga',0,    'miskin', 'tidak_sekolah','tidak_sekolah',3,2),
  ('6171010101200009','Fadhil Rahmat',    'L','2020-07-07','anak',           'belum_kawin', 'hidup','Jl. Gajah Mada No.7', -0.02360,109.32270,'',           '',              0,      'miskin', 'tidak_sekolah','tidak_sekolah',3,2),
  ('6171010101550010','Candra Wijaya',    'L','1955-12-01','kepala_keluarga','cerai_mati',  'hidup','Jl. Diponegoro No.33',-0.02800,109.33550,'081234560010','pensiunan',     2500000,'mampu',  's1',  'lulus',        4,4),
  ('6171010101850011','Rudi Hartono',     'L','1985-02-14','kepala_keluarga','kawin',       'hidup','Jl. Ahmad Yani No.88',-0.01960,109.32910,'081234560011','wiraswasta',    3000000,'mampu',  's1',  'lulus',        5,1),
  ('6171010101880012','Lina Kusuma',      'P','1988-07-30','istri',          'kawin',       'hidup','Jl. Ahmad Yani No.88',-0.01960,109.32910,'081234560012','guru',          2800000,'mampu',  's1',  'lulus',        5,1),
  ('6171010101700013','Suparman',         'L','1970-03-20','kepala_keluarga','kawin',       'hidup','Jl. Veteran No.22',   -0.02430,109.32750,'081234560013','tukang_bangunan',900000,'miskin', 'smp', 'lulus',        1,1),
  ('6171010101120014','Nurul Hidayah',    'P','2012-11-11','anak',           'belum_kawin', 'hidup','Jl. Veteran No.22',   -0.02440,109.32760,'',           'pelajar',       0,      'miskin', 'sd',  'sekolah',      1,1),
  ('6171010101920015','Bagas Setiawan',   'L','1992-05-05','kepala_keluarga','kawin',       'hidup','Jl. KH Wahid Hasyim', -0.02900,109.32500,'081234560015','ojek_online',   1200000,'rentan', 'sma', 'lulus',        NULL,2);

-- ============================================================
-- DATA AWAL: JENIS BANTUAN
-- ============================================================
INSERT INTO jenis_bantuan (nama, kategori, satuan, deskripsi) VALUES
  ('Sembako Bulanan',     'sembako',    'paket',   'Paket beras 10kg + minyak + gula'),
  ('Bantuan Pendidikan',  'pendidikan', 'rupiah',  'Biaya SPP / seragam / buku'),
  ('Bantuan Kesehatan',   'kesehatan',  'paket',   'Obat-obatan dan biaya berobat'),
  ('Modal Usaha Kecil',   'ekonomi',   'rupiah',   'Pinjaman tanpa bunga untuk usaha'),
  ('Pakaian Layak Pakai', 'lainnya',   'koli',     'Pakaian bekas layak pakai');

-- ============================================================
-- DATA AWAL: HISTORI BANTUAN
-- ============================================================
INSERT INTO histori_bantuan (penduduk_id, jenis_bantuan_id, sumber_bantuan, tanggal, jumlah, status, catatan, user_id) VALUES
  (1, 1, 'Masjid Raya Mujahidin',   '2025-01-15', 1, 'selesai',     'Periode Januari 2025', 2),
  (1, 1, 'Masjid Raya Mujahidin',   '2025-02-15', 1, 'selesai',     'Periode Februari 2025',2),
  (1, 3, 'Puskesmas Kota',          '2025-03-10', 1, 'selesai',     'Berobat influenza',    2),
  (2, 1, 'Masjid Raya Mujahidin',   '2025-01-15', 1, 'selesai',     'Periode Januari 2025', 2),
  (3, 2, 'Dinas Pendidikan',        '2025-01-20', 500000,'selesai', 'Bantuan seragam SD',   2),
  (7, 1, 'Masjid Al-Falah',         '2025-02-01', 1, 'selesai',     'Paket sembako',        2),
  (7, 3, 'Puskesmas Kota',          '2025-04-05', 1, 'disalurkan',  'Pengobatan rutin',     2),
  (8, 1, 'Masjid Al-Falah',         '2025-02-01', 1, 'selesai',     'Paket sembako',        2),
  (13,1, 'Masjid Raya Mujahidin',   '2025-03-15', 1, 'selesai',     'Paket sembako Maret',  2),
  (15,4, 'Gereja GPIB Imanuel',     '2025-05-01', 2000000,'direncanakan','Modal usaha warung',3);

-- ============================================================
-- DATA AWAL: LAPORAN MASYARAKAT
-- ============================================================
INSERT INTO laporan (nama_pelapor, penduduk_id, deskripsi, lat, lng, urgensi, status) VALUES
  ('Anonim',        7,  'Pak Darman sudah 3 hari tidak bisa makan, sakit dan tidak ada yang merawat.',  -0.02355,109.32260,'darurat',  'diverifikasi'),
  ('Ibu RT 02',     1,  'Keluarga Hasan Basri membutuhkan bantuan sembako, penghasilan turun drastis.', -0.02510,109.32810,'tinggi',   'diproses'),
  ('Warga Setempat',NULL,'Ada anak kecil di Jl. Gajah Mada yg tidak sekolah dan terlihat kurang gizi.',  -0.02360,109.32280,'tinggi',   'pending'),
  ('Bagas S.',      NULL,'Kebutuhan modal usaha kecil di kawasan Jl. KH Wahid Hasyim.',                  -0.02900,109.32500,'sedang',   'pending'),
  ('Anonim',        NULL,'Lansia sebatang kara di Jl. Diponegoro membutuhkan perhatian.',                 -0.02810,109.33560,'sedang',   'pending');

-- ============================================================
-- DATA AWAL: CHAT
-- ============================================================
INSERT INTO chat (from_user, to_user, pesan) VALUES
  (2, 3,    'Pak Budi, apakah gereja bisa bantu keluarga Widodo di Jl. Tanjungpura? Kondisi cukup memprihatinkan.'),
  (3, 2,    'Insya Allah siap. Minggu depan kami ada jadwal distribusi. Boleh koordinasi lebih lanjut.'),
  (2, NULL, '[BROADCAST] Pengumpulan sembako bulan ini dimulai 10 Juni. Mohon kontribusi semua pihak.');

-- ============================================================
-- DATA AWAL: LOG AKTIVITAS
-- ============================================================
INSERT INTO log_aktivitas (user_id, aksi, tabel, record_id, detail) VALUES
  (2,'create','penduduk',1,'Menambah data penduduk Hasan Basri'),
  (2,'create','histori_bantuan',1,'Menyalurkan sembako ke penduduk ID 1'),
  (3,'update','laporan',1,'Memverifikasi laporan darurat Darman Husin');
