-- ============================================================
-- WebGIS Pemetaan Kemiskinan Terpadu — Database Lengkap (SKPL)
-- ============================================================
-- Import file ini untuk membuat ulang database dari awal.
-- Perhatian: tabel lama dengan nama yang sama akan dihapus.

SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS activity_log;
DROP TABLE IF EXISTS foto_rumah;
DROP TABLE IF EXISTS bantuan_sosial;
DROP TABLE IF EXISTS jenis_bantuan;
DROP TABLE IF EXISTS fasilitas_publik;
DROP TABLE IF EXISTS wilayah;
DROP TABLE IF EXISTS laporan_warga;
DROP TABLE IF EXISTS warga_miskin;
DROP TABLE IF EXISTS users;

SET FOREIGN_KEY_CHECKS = 1;

-- ============================================================
-- 1. Users (4 role SKPL: publik / enumerator / operator / pimpinan)
-- ============================================================
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(120) DEFAULT NULL,
    password VARCHAR(255) NOT NULL,
    role ENUM('publik','enumerator','operator','pimpinan') NOT NULL DEFAULT 'enumerator',
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    wilayah_tugas VARCHAR(100) DEFAULT NULL,
    last_login TIMESTAMP NULL DEFAULT NULL,
    nama_lengkap VARCHAR(100) DEFAULT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Akun demo. Password: operator=admin123, pimpinan & enumerator=user123
INSERT INTO users (username, email, password, role, nama_lengkap) VALUES
    ('operator',   'operator@webgis.id',   '$2y$12$oRvX1EtLHM/y8XtwlOy./Oi2UVpnHp98GvXqEuLCFimhr0doKus62', 'operator',   'Operator Dinas Sosial'),
    ('pimpinan',   'pimpinan@webgis.id',   '$2y$12$djJkmhJBRCSCqqpAICIvGuLoVpICrDUS2IVECbZUodgR89VRTqdLW', 'pimpinan',   'Kepala Dinas Sosial'),
    ('enumerator', 'enumerator@webgis.id', '$2y$12$djJkmhJBRCSCqqpAICIvGuLoVpICrDUS2IVECbZUodgR89VRTqdLW', 'enumerator', 'Petugas Lapangan');

-- ============================================================
-- 2. Rumah Tangga Miskin
-- ============================================================
CREATE TABLE warga_miskin (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nama_kk VARCHAR(100) NOT NULL,
    nik_kk VARCHAR(16) DEFAULT NULL,
    alamat VARCHAR(255) DEFAULT NULL,
    wilayah_id INT DEFAULT NULL,
    rt VARCHAR(5) DEFAULT NULL,
    rw VARCHAR(5) DEFAULT NULL,
    jumlah_jiwa INT DEFAULT NULL,
    pekerjaan_kk VARCHAR(100) DEFAULT NULL,
    penghasilan DECIMAL(15,2) NOT NULL,
    jumlah_tanggungan INT NOT NULL,
    sumber_air ENUM('SUMUR_BOR','PDAM','SUNGAI','HUJAN','TIDAK_ADA') DEFAULT NULL,
    status_listrik ENUM('PLN','NON_PLN','TIDAK_ADA') DEFAULT NULL,
    material_dinding ENUM('PERMANEN','SEMI_PERMANEN','TIDAK_PERMANEN') DEFAULT NULL,
    status_kepemilikan ENUM('MILIK','SEWA','NUMPANG','LAINNYA') DEFAULT NULL,
    status_verifikasi ENUM('belum','terverifikasi','perlu_tinjauan') NOT NULL DEFAULT 'belum',
    created_by INT DEFAULT NULL,
    geom GEOMETRY NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    SPATIAL INDEX idx_warga_miskin_geom (geom)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO warga_miskin (nama_kk, penghasilan, jumlah_tanggungan, geom) VALUES
    ('Bpk. Budi (Terisolasi)',  800000.00, 4, ST_GeomFromText('POINT(109.361 -0.051)')),
    ('Ibu Siti (Terisolasi)',   600000.00, 2, ST_GeomFromText('POINT(109.362 -0.052)')),
    ('Bpk. Joko (Terisolasi)', 1000000.00, 5, ST_GeomFromText('POINT(109.363 -0.053)')),
    ('Ibu Ani (Terisolasi)',    700000.00, 3, ST_GeomFromText('POINT(109.364 -0.054)')),
    ('Bpk. Hasan',             1200000.00, 3, ST_GeomFromText('POINT(109.334 -0.050)')),
    ('Mbah Warno',              400000.00, 1, ST_GeomFromText('POINT(109.336 -0.046)')),
    ('Pak Junaidi',             900000.00, 4, ST_GeomFromText('POINT(109.344 -0.040)'));

-- ============================================================
-- 3. Laporan Warga (partisipasi/transparansi)
-- ============================================================
CREATE TABLE laporan_warga (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    kategori VARCHAR(50) NOT NULL,
    deskripsi TEXT NOT NULL,
    geometry POINT NOT NULL,
    status ENUM('menunggu', 'diproses', 'selesai', 'ditolak') NOT NULL DEFAULT 'menunggu',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_laporan_user_id (user_id),
    SPATIAL INDEX idx_laporan_geometry (geometry),
    CONSTRAINT fk_laporan_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- 4. Log Aktivitas (KF-04)
-- ============================================================
CREATE TABLE activity_log (
    id           INT AUTO_INCREMENT PRIMARY KEY,
    user_id      INT NULL,
    username     VARCHAR(50)  DEFAULT NULL,
    aksi         VARCHAR(50)  NOT NULL,
    tabel_target VARCHAR(50)  DEFAULT NULL,
    record_id    INT          DEFAULT NULL,
    keterangan   TEXT         DEFAULT NULL,
    ip_address   VARCHAR(45)  DEFAULT NULL,
    created_at   TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_activity_user (user_id),
    INDEX idx_activity_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- 5. Wilayah (KF-06) — batas kelurahan untuk choropleth
-- ============================================================
CREATE TABLE wilayah (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    kode_wilayah    VARCHAR(20)  DEFAULT NULL,
    nama            VARCHAR(100) NOT NULL,
    jenis           ENUM('kelurahan','kecamatan') NOT NULL DEFAULT 'kelurahan',
    parent_id       INT          DEFAULT NULL,
    jumlah_penduduk INT          NOT NULL DEFAULT 0,
    geom            GEOMETRY      NOT NULL,
    created_at      TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    SPATIAL INDEX idx_wilayah_geom (geom)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO wilayah (kode_wilayah, nama, jenis, jumlah_penduduk, geom) VALUES
    ('6171010001', 'Kel. Tambelan Sampit', 'kelurahan', 45,
        ST_GeomFromText('POLYGON((109.357 -0.047, 109.368 -0.047, 109.368 -0.058, 109.357 -0.058, 109.357 -0.047))')),
    ('6171010002', 'Kel. Sungai Bangkong', 'kelurahan', 60,
        ST_GeomFromText('POLYGON((109.328 -0.043, 109.340 -0.043, 109.340 -0.055, 109.328 -0.055, 109.328 -0.043))')),
    ('6171010003', 'Kel. Akcaya', 'kelurahan', 80,
        ST_GeomFromText('POLYGON((109.339 -0.035, 109.350 -0.035, 109.350 -0.045, 109.339 -0.045, 109.339 -0.035))')),
    ('6171010004', 'Kel. Benua Melayu Darat', 'kelurahan', 55,
        ST_GeomFromText('POLYGON((109.318 -0.044, 109.329 -0.044, 109.329 -0.056, 109.318 -0.056, 109.318 -0.044))'));

-- ============================================================
-- 6. Bantuan Sosial (KF-17) — master jenis + riwayat per warga
-- ============================================================
CREATE TABLE jenis_bantuan (
    id        INT AUTO_INCREMENT PRIMARY KEY,
    kode      VARCHAR(20) NOT NULL UNIQUE,
    nama      VARCHAR(100) NOT NULL,
    deskripsi VARCHAR(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO jenis_bantuan (kode, nama, deskripsi) VALUES
    ('PKH',     'Program Keluarga Harapan',         'Bantuan tunai bersyarat keluarga miskin'),
    ('BPNT',    'Bantuan Pangan Non Tunai',         'Bantuan sembako via KKS'),
    ('PBI-JK',  'Penerima Bantuan Iuran JK',        'Subsidi iuran BPJS Kesehatan'),
    ('BLT-DD',  'Bantuan Langsung Tunai Dana Desa', 'Bantuan tunai dari Dana Desa'),
    ('RUTILAHU','Rumah Tidak Layak Huni',           'Rehabilitasi rumah tidak layak huni'),
    ('KIP',     'Kartu Indonesia Pintar',           'Bantuan biaya pendidikan');

CREATE TABLE bantuan_sosial (
    id               INT AUTO_INCREMENT PRIMARY KEY,
    warga_id         INT NOT NULL,
    jenis_bantuan_id INT NOT NULL,
    tgl_mulai        DATE DEFAULT NULL,
    tgl_berakhir     DATE DEFAULT NULL,
    is_aktif         TINYINT(1) NOT NULL DEFAULT 1,
    keterangan       VARCHAR(255) DEFAULT NULL,
    created_at       TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_bansos_warga (warga_id),
    INDEX idx_bansos_jenis (jenis_bantuan_id),
    CONSTRAINT fk_bansos_warga FOREIGN KEY (warga_id) REFERENCES warga_miskin(id) ON DELETE CASCADE,
    CONSTRAINT fk_bansos_jenis FOREIGN KEY (jenis_bantuan_id) REFERENCES jenis_bantuan(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- 7. Foto Kondisi Rumah (KF-13)
-- ============================================================
CREATE TABLE foto_rumah (
    id         INT AUTO_INCREMENT PRIMARY KEY,
    warga_id   INT NOT NULL,
    file_path  VARCHAR(255) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_foto_warga (warga_id),
    CONSTRAINT fk_foto_warga FOREIGN KEY (warga_id) REFERENCES warga_miskin(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- 8. Fasilitas Publik (KF-21) — untuk proximity analysis
-- ============================================================
CREATE TABLE fasilitas_publik (
    id         INT AUTO_INCREMENT PRIMARY KEY,
    nama       VARCHAR(120) NOT NULL,
    jenis      ENUM('sekolah','puskesmas','pasar','kantor_kelurahan','rumah_ibadah','lainnya') NOT NULL DEFAULT 'lainnya',
    wilayah_id INT DEFAULT NULL,
    geom       GEOMETRY NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    SPATIAL INDEX idx_fasilitas_geom (geom)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO fasilitas_publik (nama, jenis, geom) VALUES
    ('SDN 01 Pontianak Kota',  'sekolah',          ST_GeomFromText('POINT(109.3380 -0.0420)')),
    ('Puskesmas Alianyang',    'puskesmas',        ST_GeomFromText('POINT(109.3330 -0.0480)')),
    ('Pasar Flamboyan',        'pasar',            ST_GeomFromText('POINT(109.3470 -0.0250)')),
    ('Kantor Kel. Akcaya',     'kantor_kelurahan', ST_GeomFromText('POINT(109.3445 -0.0400)')),
    ('Puskesmas Kampung Bali', 'puskesmas',        ST_GeomFromText('POINT(109.3360 -0.0440)'));

-- ============================================================
-- 9. Seed demo kondisi rumah & bantuan (untuk analisis Fase E/F)
-- ============================================================
UPDATE warga_miskin SET sumber_air='SUNGAI', status_listrik='NON_PLN', material_dinding='TIDAK_PERMANEN', status_kepemilikan='NUMPANG' WHERE nama_kk LIKE '%Terisolasi%';
UPDATE warga_miskin SET sumber_air='PDAM', status_listrik='PLN', material_dinding='SEMI_PERMANEN', status_kepemilikan='MILIK' WHERE nama_kk IN ('Bpk. Hasan','Mbah Warno','Pak Junaidi');

INSERT INTO bantuan_sosial (warga_id, jenis_bantuan_id, tgl_mulai, is_aktif)
SELECT id, 1, '2026-01-01', 1 FROM warga_miskin WHERE nama_kk IN ('Bpk. Hasan','Pak Junaidi');
INSERT INTO bantuan_sosial (warga_id, jenis_bantuan_id, tgl_mulai, is_aktif)
SELECT id, 2, '2026-02-01', 1 FROM warga_miskin WHERE nama_kk='Mbah Warno';
