<?php
include('../session.php');

// Error handling dan debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Debug: Cek koneksi database
if (!isset($conn)) {
    die("Error: Database connection tidak tersedia");
}

// Test koneksi database
if (mysqli_connect_errno()) {
    die("Error: Database connection failed - " . mysqli_connect_error());
}

// Validasi session dan data POST
if (!isset($u) || !is_array($u)) {
    die("Error: Session tidak valid");
}

if (!isset($_POST['title']) || !isset($_POST['content'])) {
    die("Error: Data POST tidak lengkap");
}

// Pastikan variabel $u telah didefinisikan dengan benar
$users = $u['user'];
$author = $u['full_name'];

$title = str_replace(array("'", "'"), "&apos;", $_POST['title']);
$slugs = preg_replace("/[^a-zA-Z0-9]/", "-", $title);
$slug = strtolower($slugs);
$content = str_replace(array("'", "'"), "&apos;", $_POST['content']);
$postID = isset($_POST['postID']) ? $_POST['postID'] : '';
$date = date('Y-m-d');
$kode = date('YdmHis');

// Define allowed image types
$tipe_gambar = array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/bmp', 'image/png');

// Cek apakah ada file yang diupload
$gbr = isset($_FILES['image']['name']) ? $_FILES['image']['name'] : '';
$ukuran = isset($_FILES['image']['size']) ? $_FILES['image']['size'] : 0;
$tipe = isset($_FILES['image']['type']) ? $_FILES['image']['type'] : '';
$error = isset($_FILES['image']['error']) ? $_FILES['image']['error'] : 4;

// Validasi direktori upload
$upload_dir = "../../upload/";
if (!is_dir($upload_dir)) {
    if (!mkdir($upload_dir, 0755, true)) {
        die("Error: Tidak dapat membuat direktori upload");
    }
}

// Cek permission direktori
if (!is_writable($upload_dir)) {
    die("Error: Direktori upload tidak memiliki permission write");
}

$newname = '';
if ($gbr !== "" && $error == 0) {
    // Validasi ukuran file (max 5MB)
    $max_size = 5 * 1024 * 1024; // 5MB
    if ($ukuran > $max_size) {
        header('location:../promo.php?do=add&notif=4'); // notif=4 untuk file terlalu besar
        exit();
    }
    
    $explode = explode('.', $gbr);
    $extensi = strtolower($explode[count($explode) - 1]);
    $newname = 'blog_' . $users . '_' . $kode . '.' . $extensi;
    
    // Validasi ekstensi file
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'bmp');
    if (!in_array($extensi, $allowed_extensions)) {
        header('location:../promo.php?do=add&notif=3');
        exit();
    }
}

if ($postID == '') {
    // INSERT new post
    if ($gbr !== "" && $error == 0) {
        if (in_array(strtolower($tipe), $tipe_gambar)) {
            // Cek apakah upload berhasil
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $newname)) {
                // Escape data untuk keamanan
                $slug_esc = mysqli_real_escape_string($conn, $slug);
                $title_esc = mysqli_real_escape_string($conn, $title);
                $newname_esc = mysqli_real_escape_string($conn, $newname);
                $content_esc = mysqli_real_escape_string($conn, $content);
                $author_esc = mysqli_real_escape_string($conn, $author);
                $users_esc = mysqli_real_escape_string($conn, $users);
                
                // PERBAIKAN: Sesuaikan dengan struktur database
                $query = "INSERT INTO `tb_post` (`slug`, `title`, `image`, `content`, `author`, `kategori`, `created_date`, `last_update`, `user`, `status`) VALUES ('$slug_esc', '$title_esc', '$newname_esc', '$content_esc', '$author_esc', 1, '$date', '$date', '$users_esc', 1)";
                
                if (mysqli_query($conn, $query)) {
                    header('location:../promo.php?notif=1');
                } else {
                    // Hapus file yang sudah diupload jika query gagal
                    unlink($upload_dir . $newname);
                    error_log("Database Error: " . mysqli_error($conn));
                    header('location:../promo.php?notif=5'); // notif=5 untuk error database
                }
            } else {
                header('location:../promo.php?notif=6'); // notif=6 untuk gagal upload file
            }
        } else {
            header('location:../promo.php?notif=3');
        }
    } else {
        // Insert tanpa gambar
        $slug_esc = mysqli_real_escape_string($conn, $slug);
        $title_esc = mysqli_real_escape_string($conn, $title);
        $content_esc = mysqli_real_escape_string($conn, $content);
        $author_esc = mysqli_real_escape_string($conn, $author);
        $users_esc = mysqli_real_escape_string($conn, $users);
        
        // PERBAIKAN: Sesuaikan dengan struktur database
        $query = "INSERT INTO `tb_post` (`slug`, `title`, `image`, `content`, `author`, `kategori`, `created_date`, `last_update`, `user`, `status`) VALUES ('$slug_esc', '$title_esc', 'no-photo.jpg', '$content_esc', '$author_esc', 1, '$date', '$date', '$users_esc', 1)";
        
        if (mysqli_query($conn, $query)) {
            header('location:../promo.php?notif=1');
        } else {
            error_log("Database Error: " . mysqli_error($conn));
            header('location:../promo.php?notif=5');
        }
    }
} else {
    // UPDATE existing post
    if ($gbr !== "" && $error == 0) {
        if (in_array(strtolower($tipe), $tipe_gambar)) {
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $newname)) {
                // Hapus gambar lama jika ada
                $postID_esc = mysqli_real_escape_string($conn, $postID);
                $old_image_query = mysqli_query($conn, "SELECT image FROM tb_post WHERE cuid = '$postID_esc'");
                if ($old_image_query && $row = mysqli_fetch_assoc($old_image_query)) {
                    $old_image = $row['image'];
                    if ($old_image != 'no-photo.jpg' && file_exists($upload_dir . $old_image)) {
                        unlink($upload_dir . $old_image);
                    }
                }
                
                // Escape data untuk keamanan
                $slug_esc = mysqli_real_escape_string($conn, $slug);
                $title_esc = mysqli_real_escape_string($conn, $title);
                $newname_esc = mysqli_real_escape_string($conn, $newname);
                $content_esc = mysqli_real_escape_string($conn, $content);
                $author_esc = mysqli_real_escape_string($conn, $author);
                $users_esc = mysqli_real_escape_string($conn, $users);
                
                $query = "UPDATE `tb_post` SET `slug` = '$slug_esc', `title` = '$title_esc', `image` = '$newname_esc', `content` = '$content_esc', `author` = '$author_esc', `last_update` = '$date', `user` = '$users_esc' WHERE cuid = '$postID_esc'";
                
                if (mysqli_query($conn, $query)) {
                    header('location:../promo.php?postID=' . $postID . '&notif=1');
                } else {
                    unlink($upload_dir . $newname);
                    error_log("Database Error: " . mysqli_error($conn));
                    header('location:../promo.php?postID=' . $postID . '&notif=5');
                }
            } else {
                header('location:../promo.php?postID=' . $postID . '&notif=6');
            }
        } else {
            header('location:../promo.php?postID=' . $postID . '&notif=3');
        }
    } else {
        // Update tanpa mengubah gambar
        $slug_esc = mysqli_real_escape_string($conn, $slug);
        $title_esc = mysqli_real_escape_string($conn, $title);
        $content_esc = mysqli_real_escape_string($conn, $content);
        $author_esc = mysqli_real_escape_string($conn, $author);
        $users_esc = mysqli_real_escape_string($conn, $users);
        $postID_esc = mysqli_real_escape_string($conn, $postID);
        
        $query = "UPDATE `tb_post` SET `slug` = '$slug_esc', `title` = '$title_esc', `content` = '$content_esc', `author` = '$author_esc', `last_update` = '$date', `user` = '$users_esc' WHERE cuid = '$postID_esc'";
        
        if (mysqli_query($conn, $query)) {
            header('location:../promo.php?postID=' . $postID . '&notif=1');
        } else {
            error_log("Database Error: " . mysqli_error($conn));
            header('location:../promo.php?postID=' . $postID . '&notif=5');
        }
    }
}

exit();
?>