<?php
header('Content-Type: application/json');

error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'koneksi.php'; // Pastikan $conn aktif[cite: 4]

$method = $_SERVER['REQUEST_METHOD']; //[cite: 4]

/* =====================================================
   GET DATA
===================================================== */
if ($method == 'GET') { //[cite: 4]

    if (!isset($_GET['id_distributor']) || empty($_GET['id_distributor'])) { //[cite: 4]
        echo json_encode([
            "status" => "error",
            "message" => "ID Distributor tidak valid"
        ]); //[cite: 4]
        exit; //[cite: 4]
    }

    $id_distributor = intval($_GET['id_distributor']); //[cite: 4]

    /* ==========================================
        Ambil 12 tanggal opname terakhir
        beserta Nama Karyawan
    ========================================== */
    $tgl_sql = "
        SELECT
            DATE_FORMAT(r.tanggal_stok, '%d-%m-%Y') AS tgl,
            MAX(r.tanggal_stok) AS urut,
            MAX(k.nama) AS nama_karyawan
        FROM riwayat_stok_opname r
        LEFT JOIN karyawan k ON r.id_karyawan = k.no_kartu
        WHERE r.id_distributor = $id_distributor
        GROUP BY DATE_FORMAT(r.tanggal_stok, '%d-%m-%Y')
        ORDER BY urut DESC
        LIMIT 12
    "; //[cite: 4]

    $tgl_res = $conn->query($tgl_sql); //[cite: 4]

    if (!$tgl_res) { //[cite: 4]
        echo json_encode([
            "status" => "error",
            "message" => "Error pada Query Tanggal: " . $conn->error
        ]); //[cite: 4]
        exit; //[cite: 4]
    }

    $list_tanggal = []; //[cite: 4]
    $karyawan_per_tanggal = []; //[cite: 4]

    while ($row = $tgl_res->fetch_assoc()) { //[cite: 4]
        $tgl_formatted = $row['tgl']; //[cite: 4]
        $list_tanggal[] = $tgl_formatted; //[cite: 4]
        
        $karyawan_per_tanggal[$tgl_formatted] = !empty($row['nama_karyawan']) 
            ? $row['nama_karyawan'] 
            : '-'; //[cite: 4]
    }

    $list_tanggal = array_reverse($list_tanggal); //[cite: 4]

    /* ==========================================
        Ambil Produk
    ========================================== */
    $sql = "
        SELECT
            id_produk_master,
            nama_barang,
            kode_barang,
            harga_satuan
        FROM produk_master
        WHERE id_distributor = $id_distributor
        ORDER BY nama_barang
    "; //[cite: 4]

    $result = $conn->query($sql); //[cite: 4]

    if (!$result) { //[cite: 4]
        echo json_encode([
            "status" => "error",
            "message" => "Error pada Query Produk: " . $conn->error
        ]); //[cite: 4]
        exit; //[cite: 4]
    }

    $produk = []; //[cite: 4]

    while ($row = $result->fetch_assoc()) { //[cite: 4]

        $id_pm = $row['id_produk_master']; //[cite: 4]
        $riwayat = []; //[cite: 4]

        foreach ($list_tanggal as $tgl) { //[cite: 4]

            $stok_sql = "
                SELECT stok_terbaru
                FROM riwayat_stok_opname
                WHERE id_produk_master = $id_pm
                AND DATE_FORMAT(tanggal_stok, '%d-%m-%Y') = '$tgl'
                ORDER BY tanggal_stok DESC
                LIMIT 1
            "; //[cite: 4]

            $stok_res = $conn->query($stok_sql); //[cite: 4]

            if ($stok_res && $stok_res->num_rows > 0) { //[cite: 4]
                $stok = $stok_res->fetch_assoc(); //[cite: 4]
                $riwayat[$tgl] = (int)$stok['stok_terbaru']; //[cite: 4]
            } else {
                $riwayat[$tgl] = "-"; //[cite: 4]
            }
        }

        // Stok terakhir (kemaren)
        $last_sql = "
            SELECT stok_terbaru
            FROM riwayat_stok_opname
            WHERE id_produk_master = $id_pm
            ORDER BY tanggal_stok DESC
            LIMIT 1
        "; //[cite: 4]

        $last_res = $conn->query($last_sql); //[cite: 4]
        $stok_kemaren = 0; //[cite: 4]

        if ($last_res && $last_res->num_rows > 0) { //[cite: 4]
            $stok_kemaren = intval($last_res->fetch_assoc()['stok_terbaru']); //[cite: 4]
        }

        $produk[] = [
            "id_produk_master" => (int)$id_pm,
            "nama_barang"      => $row['nama_barang'],
            "kode_barang"      => $row['kode_barang'],
            "harga_satuan"     => (int)$row['harga_satuan'],
            "stok_kemaren"     => $stok_kemaren,
            "riwayat"          => empty($riwayat) ? (object)[] : $riwayat
        ]; //[cite: 4]
    }

    echo json_encode([
        "status"               => "success",
        "tanggal_headers"      => $list_tanggal,
        "karyawan_per_tanggal" => $karyawan_per_tanggal,
        "produk_data"          => $produk
    ]); //[cite: 4]

    exit; //[cite: 4]
}


/* =====================================================
   SIMPAN DATA (STOK OPNAME / PREORDER)
===================================================== */
if ($method == 'POST') {

    // Bersihkan buffer agar tidak ada karakter ekstra/HTML sebelum JSON
    if (ob_get_length()) {
    ob_clean();
}
    header('Content-Type: application/json');

    $input = json_decode(file_get_contents("php://input"), true);

    if (!$input) {
        echo json_encode([
            "status" => "error",
            "message" => "JSON tidak valid"
        ]);
        exit;
    }

    // A. PENYIMPANAN PURCHASE ORDER (PREORDER)
    if (isset($input["data_po"]) && is_array($input["data_po"])) {
        
        $id_distributor = intval($input["id_distributor"] ?? 0);
        $data_po        = $input["data_po"];

        if ($id_distributor == 0 || empty($data_po)) {
            echo json_encode([
                "status"  => "error",
                "message" => "Data PO atau ID Distributor kosong"
            ]);
            exit;
        }

        // Generate Nomor PO unik (Format: PO-YYYYMMDD-HIS)
        $no_po = "PO-" . date("Ymd-His");

        $conn->begin_transaction();

        try {
            // 1. Simpan Header Ke Tabel preorder
            $stmtHeader = $conn->prepare("INSERT INTO preorder (no_po, id_distributor) VALUES (?, ?)");
            if (!$stmtHeader) {
                throw new Exception("Error prepare header: " . $conn->error);
            }
            
            $stmtHeader->bind_param("si", $no_po, $id_distributor);
            $stmtHeader->execute();
            
            // Mengambil insert_id langsung dari objek koneksi ($conn), BUKAN $stmtHeader
            $id_po_baru = $conn->insert_id; 
            $stmtHeader->close();

            // 2. Prepare Query Detail
            $stmtDetail = $conn->prepare("INSERT INTO detail_po (id_po, id_produk_master, nama_barang, jumlah, jenis, keterangan) VALUES (?, ?, ?, ?, ?, ?)");
            if (!$stmtDetail) {
                throw new Exception("Error prepare detail: " . $conn->error);
            }

            foreach ($data_po as $item) {
                $id_pm       = intval($item["id_produk_master"] ?? 0);
                $nama_barang = trim($item["nama_barang"] ?? "");
                $jumlah      = intval($item["jumlah"] ?? 0);
                $jenis       = trim($item["jenis"] ?? "pcs");
                $keterangan  = trim($item["keterangan"] ?? "");

                // Jika nama_barang kosong dari Flutter, cari dari DB secara manual
                if (empty($nama_barang) && $id_pm > 0) {
                    $resNama = $conn->query("SELECT nama_barang FROM produk_master WHERE id_produk_master = $id_pm LIMIT 1");
                    if ($resNama && $rowNama = $resNama->fetch_assoc()) {
                        $nama_barang = $rowNama["nama_barang"];
                    }
                }

                // Hanya simpan item yang jumlah ordernya lebih dari 0
                if ($jumlah > 0) {
                   $stmtDetail->bind_param(
    "iisiss",
    $id_po_baru,
    $id_pm,
    $nama_barang,
    $jumlah,
    $jenis,
    $keterangan
);
                    $stmtDetail->execute();
                }
            }

            $stmtDetail->close();

            $conn->commit();

            echo json_encode([
                "status"  => "success",
                "message" => "Purchase Order berhasil disimpan!",
                "no_po"   => $no_po
            ]);

        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode([
                "status"  => "error",
                "message" => "Gagal simpan PO: " . $e->getMessage()
            ]);
        }

        exit;
    }

    // B. JIKA INI ADALAH PENYIMPANAN STOK OPNAME BIASA
    $id_distributor = intval($input["id_distributor"] ?? 0);
    $id_karyawan    = $conn->real_escape_string($input["id_karyawan"] ?? "");
    $data_stok      = $input["data_stok"] ?? [];

    if ($id_distributor == 0 || empty($id_karyawan) || !is_array($data_stok)) {
        echo json_encode([
            "status" => "error",
            "message" => "Parameter stok opname tidak lengkap"
        ]);
        exit;
    }

    $conn->begin_transaction();

    try {

        foreach ($data_stok as $item) {

            $id_pm        = intval($item["id_produk_master"]);
            $stok_kemaren = intval($item["stok_kemaren"]);
            $stok_terbaru = intval($item["stok_terbaru"]);
            $keterangan   = $conn->real_escape_string($item["keterangan"] ?? "");

            $sql = "
                INSERT INTO riwayat_stok_opname
                (
                    id_produk_master,
                    id_distributor,
                    id_karyawan,
                    stok_kemaren,
                    stok_terbaru,
                    keterangan,
                    tanggal_stok
                )
                VALUES
                (
                    $id_pm,
                    $id_distributor,
                    '$id_karyawan',
                    $stok_kemaren,
                    $stok_terbaru,
                    '$keterangan',
                    NOW()
                )";

            if (!$conn->query($sql)) {
                throw new Exception($conn->error);
            }
        }

        $conn->commit();

        echo json_encode([
            "status" => "success"
        ]);

    } catch (Exception $e) {

        $conn->rollback();

        echo json_encode([
            "status" => "error",
            "message" => $e->getMessage()
        ]);
    }

    exit;
}

echo json_encode([
    "status" => "error",
    "message" => "Method tidak didukung"
]); //[cite: 4]

$conn->close(); //[cite: 4]
?>