-- =====================================================================
-- MIGRASI PERPUSTAKAAN KITAB - SIAP IMPORT VIA PHPMYADMIN
-- ---------------------------------------------------------------------
-- File ini HANYA BERISI QUERY BACA (SELECT). Tidak ada CREATE, ALTER,
-- DELETE, DROP, atau UPDATE yang aktif. Import file ini TIDAK mengubah
-- data apa pun dan AMAN dijalankan berulang kali.
--
-- Kompatibel dengan akun database hosting biasa: file ini TIDAK membaca
-- `information_schema` sama sekali (menghindari error #1044 Access denied
-- for user ... to database information_schema).
--
-- Referensi struktur: manuputr_perpus_kitab.sql (dump produksi).
-- Seluruh tabel & kolom yang dibutuhkan SUDAH ADA di database produksi,
-- sehingga tidak diperlukan perubahan skema.
--
-- CARA PAKAI:
--   1. Buka phpMyAdmin -> pilih database -> tab "Import".
--   2. Pilih file ini -> Go.
--   3. Baca hasil tiap SELECT. Bandingkan dengan kolom "HARAP" di bawah.
--
-- Bila ada baris yang hasilnya TIDAK sesuai "HARAP", JANGAN lanjut ke
-- langkah rebuild. Laporkan angka yang muncul.
-- =====================================================================

SET NAMES utf8mb4;

-- =====================================================================
-- LANGKAH 1 - CEK KESIAPAN SKEMA (READ-ONLY, TANPA information_schema)
-- ---------------------------------------------------------------------
-- Setiap SELECT di bawah hanya membaca tabel aplikasi biasa. Bila kolom
-- yang disebut TIDAK ADA, MySQL/MariaDB akan menampilkan pesan
-- "Unknown column ..." pada query tersebut. Itu berarti skema database
-- Anda belum lengkap dan perlu dilengkapi manual (lihat catatan di
-- bagian bawah file).
-- =====================================================================

-- 1a. Kolom sections.parent_id, tipe_bagian, needs_review, apply_source
SELECT '1a. sections: parent_id/tipe_bagian/needs_review/apply_source' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: > 0 (kolom lengkap)' AS `harap`
FROM `sections`
WHERE `parent_id` IS NOT NULL
   OR `tipe_bagian` IS NOT NULL
   OR `needs_review` IS NOT NULL
   OR `apply_source` IS NOT NULL;

-- 1b. Kolom books.struktur_status
SELECT '1b. books: struktur_status' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: > 0 (kolom ada)' AS `harap`
FROM `books`
WHERE `struktur_status` IS NOT NULL;

-- 1c. Kolom bab_pages.section_id
SELECT '1c. bab_pages: section_id' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: >= 0 (kolom ada)' AS `harap`
FROM `bab_pages`
WHERE `section_id` IS NOT NULL;

-- 1d. Kolom content_blocks yang dipakai generator
SELECT '1d. content_blocks: text_arab/sort_order/section_id' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: >= 0 (kolom ada)' AS `harap`
FROM `content_blocks`
WHERE `text_arab` IS NOT NULL
   OR `sort_order` IS NOT NULL
   OR `section_id` IS NOT NULL;

-- =====================================================================
-- LANGKAH 2 - CEK NILAI ENUM (READ-ONLY)
-- ---------------------------------------------------------------------
-- Memastikan tidak ada nilai status di luar ENUM yang didefinisikan.
-- Semua hasil HARUS 0. Bila tidak 0, ada data lama yang perlu
-- diperbaiki manual SEBELUM rebuild.
-- =====================================================================

-- 2a. ai_generation_logs.status hanya boleh 'success' / 'failed'
SELECT '2a. ai_generation_logs.status di luar success/failed' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `ai_generation_logs`
WHERE `status` NOT IN ('success','failed');

-- 2b. ai_analyses.status hanya boleh 'draft' / 'published'
SELECT '2b. ai_analyses.status di luar draft/published' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `ai_analyses`
WHERE `status` NOT IN ('draft','published');

-- 2c. ai_contents.status hanya boleh 'draft' / 'published'
SELECT '2c. ai_contents.status di luar draft/published' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `ai_contents`
WHERE `status` NOT IN ('draft','published');

-- 2d. ai_analyses.jenis_analisis hanya 6 jenis
SELECT '2d. ai_analyses.jenis_analisis di luar 6 jenis' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `ai_analyses`
WHERE `jenis_analisis` NOT IN
      ('terjemah','perlafadz','nahwu','shorof','syarah','kesimpulan');

-- =====================================================================
-- LANGKAH 3 - HITUNG DATA TURUNAN YANG AKAN DIBANGUN ULANG (READ-ONLY)
-- ---------------------------------------------------------------------
-- Angka ini adalah JUMLAH BARIS SAAT INI. Catat sebagai bukti sebelum
-- pembersihan. File ini TIDAK menghapus apa pun.
--
-- Bila Anda ingin membersihkan data turunan lama, jalankan perintah
-- DELETE secara MANUAL (lihat blok komentar di LANGKAH 4).
-- =====================================================================

SELECT '3A. ai_analyses (turunan)' AS `pemeriksaan`, COUNT(*) AS `nilai` FROM `ai_analyses`;
SELECT '3B. category_sources (turunan)' AS `pemeriksaan`, COUNT(*) AS `nilai` FROM `category_sources`;
SELECT '3C. content_categories (turunan)' AS `pemeriksaan`, COUNT(*) AS `nilai` FROM `content_categories`;
SELECT '3D. ai_contents (turunan)' AS `pemeriksaan`, COUNT(*) AS `nilai` FROM `ai_contents`;
SELECT '3E. ai_generation_logs (riwayat)' AS `pemeriksaan`, COUNT(*) AS `nilai` FROM `ai_generation_logs`;
SELECT '3F. content_blocks (turunan)' AS `pemeriksaan`, COUNT(*) AS `nilai` FROM `content_blocks`;

-- =====================================================================
-- LANGKAH 4 - PEMBERSIHAN DATA TURUNAN (MANUAL, TIDAK OTOMATIS)
-- ---------------------------------------------------------------------
-- Semua perintah di bawah DIBERI KOMENTAR. File ini tidak akan
-- menghapus data apa pun saat diimpor.
--
-- Bila Anda ingin membersihkan data turunan lama, buka komentar pada
-- blok yang sesuai, lalu jalankan lewat tab "SQL" phpMyAdmin.
--
-- URUTAN WAJIB (anak dulu, induk belakangan) agar tidak melanggar FK:
--   ai_analyses      -> FK ke content_categories
--   category_sources -> FK ke content_categories
--   content_categories (induk) dihapus setelah kedua anaknya
--
-- YANG TIDAK BOLEH DIHAPUS (sumber asli):
--   books, categories, chapters, sections, section_texts,
--   section_text_divisions, bab_pages, kitab_struktur_drafts,
--   kitab_struktur_logs, kitab_text_batches, admins, settings
-- =====================================================================

-- DELETE FROM `ai_analyses`;
-- DELETE FROM `category_sources`;
-- DELETE FROM `content_categories`;
-- DELETE FROM `ai_contents`;
-- DELETE FROM `ai_generation_logs`;
-- DELETE FROM `content_blocks`;

-- =====================================================================
-- LANGKAH 5 - VERIFIKASI (HASIL DITAMPILKAN DI PHPMYADMIN)
-- =====================================================================

SELECT '5.1 Jumlah teks sumber kitab (TIDAK BOLEH BERUBAH)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'catat angkanya' AS `harap`
FROM `section_texts`;

SELECT '5.2 Jumlah section (TIDAK BOLEH BERUBAH)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'catat angkanya' AS `harap`
FROM `sections`;

SELECT '5.3 Section bertipe bab (wadah teks BAB)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'catat angkanya' AS `harap`
FROM `sections`
WHERE `tipe_bagian` = 'bab';

SELECT '5.4 Section bertipe subbab' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'catat angkanya' AS `harap`
FROM `sections`
WHERE `tipe_bagian` <> 'bab';

SELECT '5.5 Content blocks saat ini (0 = siap rebuild)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0 bila sudah dibersihkan' AS `harap`
FROM `content_blocks`;

SELECT '5.6 Content blocks tanpa section_id (BAB-direct)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'informasi' AS `harap`
FROM `content_blocks`
WHERE `section_id` IS NULL;

SELECT '5.7 Content blocks dengan section_id (SUBBAB)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'informasi' AS `harap`
FROM `content_blocks`
WHERE `section_id` IS NOT NULL;

SELECT '5.8 Content blocks yatim - chapter tidak ada' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `content_blocks` cb
LEFT JOIN `chapters` c ON c.`id` = cb.`chapter_id`
WHERE c.`id` IS NULL;

SELECT '5.9 Content blocks yatim - section tidak ada' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `content_blocks` cb
LEFT JOIN `sections` s ON s.`id` = cb.`section_id`
WHERE cb.`section_id` IS NOT NULL AND s.`id` IS NULL;

SELECT '5.10 Content blocks section beda BAB' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `content_blocks` cb
JOIN `sections` s ON s.`id` = cb.`section_id`
WHERE s.`chapter_id` <> cb.`chapter_id`;

SELECT '5.11 Content blocks teks kosong' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM `content_blocks`
WHERE `text_arab` IS NULL OR TRIM(`text_arab`) = '';

SELECT '5.12 Content blocks sort_order duplikat dalam 1 BAB' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'HARAP: 0' AS `harap`
FROM (
  SELECT `chapter_id`, `sort_order`
  FROM `content_blocks`
  GROUP BY `chapter_id`, `sort_order`
  HAVING COUNT(*) > 1
) AS `dup`;

SELECT '5.13 Analisis AI tersimpan (ai_analyses)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'informasi' AS `harap`
FROM `ai_analyses`;

SELECT '5.14 Analisis AI per BAB tersimpan (ai_contents)' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'informasi' AS `harap`
FROM `ai_contents`;

SELECT '5.15 Section tanpa teks sumber' AS `pemeriksaan`,
       COUNT(*) AS `nilai`,
       'informasi' AS `harap`
FROM `sections` s
LEFT JOIN `section_texts` st ON st.`section_id` = s.`id`
WHERE st.`id` IS NULL;

SELECT '5.16 Section tipe bab yang punya teks (unit BAB-direct)' AS `pemeriksaan`,
       COUNT(DISTINCT s.`id`) AS `nilai`,
       'catat angkanya' AS `harap`
FROM `sections` s
JOIN `section_texts` st ON st.`section_id` = s.`id`
WHERE s.`tipe_bagian` = 'bab';

SELECT '5.17 Section tipe subbab yang punya teks (unit SUBBAB)' AS `pemeriksaan`,
       COUNT(DISTINCT s.`id`) AS `nilai`,
       'catat angkanya' AS `harap`
FROM `sections` s
JOIN `section_texts` st ON st.`section_id` = s.`id`
WHERE s.`tipe_bagian` <> 'bab';

-- =====================================================================
-- SELESAI.
-- ---------------------------------------------------------------------
-- Langkah berikutnya: jalankan skrip PHP rebuild Content Blocks
-- (database/REBUILD_CONTENT_BLOCKS.php) lewat SSH:
--     php database/REBUILD_CONTENT_BLOCKS.php
--
-- Angka yang WAJIB dicatat sebelum rebuild:
--   * 5.1 (section_texts) -> sumber asli, harus tetap sama sesudahnya
--   * 5.2 (sections)      -> struktur kitab, harus tetap sama sesudahnya
--   * 5.16 & 5.17         -> jumlah unit yang akan dibangun ulang
--
-- BILA ADA ERROR "Unknown column" pada LANGKAH 1:
--   Skema database Anda belum lengkap. Tambahkan kolom yang disebut
--   pada pesan error secara manual lewat phpMyAdmin (tab "Structure"),
--   lalu import ulang file ini. Kolom yang dimaksud:
--     sections.parent_id        bigint(20) UNSIGNED NULL
--     sections.tipe_bagian      varchar(32) NOT NULL DEFAULT 'subbab'
--     sections.needs_review     tinyint(1) NOT NULL DEFAULT 0
--     sections.apply_source     varchar(32) NULL
--     books.struktur_status     enum('draft','review','approved','published')
--                               NOT NULL DEFAULT 'draft'
--     bab_pages.section_id      bigint(20) UNSIGNED NULL
-- =====================================================================
