DROP DATABASE IF EXISTS webgis_miskin;
CREATE DATABASE webgis_miskin CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE webgis_miskin;

CREATE TABLE admins (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    nama VARCHAR(100) NOT NULL DEFAULT 'Administrator',
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

INSERT INTO admins (username, password_hash, nama) VALUES
('admin', '$2y$10$7O061pVz/aZ5YNK/fQyYIePIPnzDb.uZn38pC/Te3s7gRyko20dIK', 'Administrator');

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 DECIMAL(10, 8) NOT NULL,
    lng DECIMAL(11, 8) NOT NULL,
    radius INT NOT NULL DEFAULT 500,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE penduduk_miskin (
    id INT AUTO_INCREMENT PRIMARY KEY,
    kk_nama VARCHAR(150) NOT NULL,
    kk_nik VARCHAR(20),
    alamat TEXT,
    lat DECIMAL(10, 8) NOT NULL,
    lng DECIMAL(11, 8) NOT NULL,
    ibadah_id INT NULL,
    jarak_m DECIMAL(10, 2) NULL,
    jarak_rute_m DECIMAL(10, 2) NULL,
    is_blank_spot TINYINT(1) NOT NULL DEFAULT 1,
    status_bantuan ENUM('Sudah dibantu', 'Belum dibantu', 'Menunggu verifikasi') NOT NULL DEFAULT 'Belum dibantu',
    kategori_kebutuhan VARCHAR(100),
    deskripsi_kebutuhan TEXT,
    tindak_lanjut VARCHAR(60) NOT NULL DEFAULT 'Belum disurvei',
    kondisi_rumah VARCHAR(80),
    penghasilan INT,
    catatan_survei TEXT,
    bukti_file VARCHAR(255),
    skor_prioritas INT NOT NULL DEFAULT 0,
    jenis_bantuan VARCHAR(100),
    tanggal_bantuan DATE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (ibadah_id) REFERENCES rumah_ibadah(id) ON DELETE SET NULL
) ENGINE=InnoDB;

CREATE TABLE anggota_keluarga (
    id INT AUTO_INCREMENT PRIMARY KEY,
    penduduk_id INT NOT NULL,
    nama VARCHAR(150) NOT NULL,
    hubungan VARCHAR(50) NOT NULL,
    umur INT,
    pekerjaan VARCHAR(100),
    FOREIGN KEY (penduduk_id) REFERENCES penduduk_miskin(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE riwayat_bantuan (
    id INT AUTO_INCREMENT PRIMARY KEY,
    penduduk_id INT NOT NULL,
    jenis_bantuan VARCHAR(120) NOT NULL,
    tanggal_bantuan DATE NOT NULL,
    nilai_bantuan VARCHAR(80),
    pemberi_bantuan VARCHAR(120),
    catatan TEXT,
    bukti_file VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (penduduk_id) REFERENCES penduduk_miskin(id) ON DELETE CASCADE
) ENGINE=InnoDB;
