 <?php

require_once "config.php";

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

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $ckodekelurahan = isset($_GET['ckodekelurahan']) ? $_GET['ckodekelurahan'] : '';
        $namaLokasi = isset($_GET['namaLokasi']) ? $_GET['namaLokasi'] : '';
        $alamat = isset($_GET['alamat']) ? $_GET['alamat'] : '';
        $note = isset($_GET['note']) ? $_GET['note'] : '';
        $ckodecust = isset($_GET['ckodecust']) ? $_GET['ckodecust'] : '';

        if (empty($ckodekelurahan) || empty($namaLokasi) || empty($alamat) || empty($note) || empty($ckodecust)) {
            echo json_encode(["success" => "false", "error" => "Missing required parameters", "message" => "Please provide all the required parameters."]);
            exit;
        }

        $query = $conn->prepare("
            SELECT 
                ckodekelurahan, cnamakelurahan, ckodekecamatan, cnamakecamatan, 
                ckodekota, cnamakota, ckodeprovinsi, cnamarovinsi, ckodepos 
            FROM tblokasi 
            WHERE ckodekelurahan = ? 
            ORDER BY cnamakelurahan ASC
        ");
        $query->bind_param("s", $ckodekelurahan);
        $query->execute();
        $result = $query->get_result();

        if ($result->num_rows > 0) {
            $locationData = $result->fetch_assoc();

            $checkLastCnoidQuery = $conn->prepare("SELECT cnoid FROM tbalamatkirim WHERE ckodecust = ? ORDER BY cnoid DESC LIMIT 1");
            $checkLastCnoidQuery->bind_param("s", $ckodecust);
            $checkLastCnoidQuery->execute();
            $checkLastCnoidResult = $checkLastCnoidQuery->get_result();
            $newCnoid = "001";

            if ($checkLastCnoidResult->num_rows > 0) {
                $lastCnoidData = $checkLastCnoidResult->fetch_assoc();
                $lastCnoid = $lastCnoidData['cnoid'];
                $newCnoid = str_pad((intval($lastCnoid) + 1), 3, "0", STR_PAD_LEFT);
            }

            $insertQuery = $conn->prepare("
                INSERT INTO tbalamatkirim (
                    ckodecust, clokasi, calamat1, calamat2, 
                    ckodeprov, cnamaprov, ckodekota, cnamakota, 
                    ckodekecamatan, cnamakecamatan, ckodekelurahan, 
                    cnamakelurahan, ckodepos, cnote, cnoid
                ) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $clokasi = $namaLokasi;    
            $calamat1 = $alamat; 
            $calamat2 = '';        
            $ckodeprov = $locationData['ckodeprovinsi'];
            $cnamaprov = $locationData['cnamarovinsi'];
            $ckodekota = $locationData['ckodekota'];
            $cnamakota = $locationData['cnamakota'];
            $ckodekecamatan = $locationData['ckodekecamatan'];
            $cnamakecamatan = $locationData['cnamakecamatan'];
            $ckodekelurahan = $locationData['ckodekelurahan'];
            $cnamakelurahan = $locationData['cnamakelurahan'];
            $ckodepos = $locationData['ckodepos'];
            $cnote = $note;

            $insertQuery->bind_param("sssssssssssssss", 
                $ckodecust, $clokasi, $calamat1, $calamat2, 
                $ckodeprov, $cnamaprov, $ckodekota, $cnamakota, 
                $ckodekecamatan, $cnamakecamatan, $ckodekelurahan, 
                $cnamakelurahan, $ckodepos, $cnote, $newCnoid
            );
            

            if ($insertQuery->execute()) {
                echo json_encode([
                    "success" => "true", 
                    "message" => "Data inserted successfully"
                ]);
            } else {
                echo json_encode([
                    "success" => "false", 
                    "error" => "Failed to insert data",
                    "message" => "Data insertion failed. Please try again."
                ]);
            }

            $insertQuery->close();
        } else {
            echo json_encode([
                "success" => "false", 
                "error" => "No matching location found for the provided ckodekelurahan",
                "message" => "The provided ckodekelurahan does not match any locations."
            ]);
        }

        $result->close();
        $query->close();
        break;

    default:
        echo json_encode(["error" => "Invalid request method"]);
        break;
}

mysqli_close($conn);
?>
