<?php
session_start();
include '../../koneksi.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../login/");
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = $_SESSION['user_id'];
    $nama_usaha = $_POST['nama_usaha'];
    $alamat_usaha = $_POST['alamat_usaha'];
    $google_maps = $_POST['google_maps'];
    $facebook = !empty($_POST['facebook']) ? $_POST['facebook'] : NULL;
    $instagram = !empty($_POST['instagram']) ? $_POST['instagram'] : NULL;

    // Cek apakah data usaha sudah ada
    $stmt = $conn->prepare("SELECT id_usaha, nama_usaha FROM datausaha WHERE id_user = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data_usaha = $result->fetch_assoc();
    $stmt->close();

    if ($data_usaha) {
        $old_nama_usaha = $data_usaha['nama_usaha'];

        // Ambil slug_url lama
        $stmt = $conn->prepare("SELECT slug_url FROM landingpage WHERE id_user = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $stmt->bind_result($old_slug);
        $stmt->fetch();
        $stmt->close();

        // Slug baru
        $slug_url = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $nama_usaha), '-'));

        // Update datausaha (selalu diupdate)
        $stmt = $conn->prepare("UPDATE datausaha SET nama_usaha = ?, alamat = ?, alamat_gmaps = ?, username_fb = ?, username_ig = ? WHERE id_user = ?");
        $stmt->bind_param("sssssi", $nama_usaha, $alamat_usaha, $google_maps, $facebook, $instagram, $user_id);
        if ($stmt->execute()) {
            $_SESSION['success'] = "Data usaha berhasil diperbarui!";
        } else {
            $_SESSION['error'] = "Gagal memperbarui data usaha!";
        }
        $stmt->close();

        // Update slug jika berubah
        if ($old_slug !== $slug_url) {
            $stmt = $conn->prepare("UPDATE landingpage SET slug_url = ? WHERE id_user = ?");
            $stmt->bind_param("si", $slug_url, $user_id);
            if ($stmt->execute()) {
                $old_folder = "../../page/" . $old_slug;
                $new_folder = "../../page/" . $slug_url;
                if (is_dir($old_folder) && !is_dir($new_folder)) {
                    rename($old_folder, $new_folder);
                }
            }
            $stmt->close();
        }

    } else {
        $_SESSION['error'] = "Data usaha tidak ditemukan!";
    }

    $conn->close();
    header("Location: ../data-usaha");
    exit();
}
?>
