HEX
Server: LiteSpeed
System: Linux in-mum-web921.main-hosting.eu 4.18.0-553.34.1.lve.el8.x86_64 #1 SMP Thu Jan 9 16:30:32 UTC 2025 x86_64
User: u590867752 (590867752)
PHP: 8.2.33
Disabled: NONE
Upload Files
File: /home/u590867752/domains/himanshuartinstitute.com/public_html/wall/user/create-post.php
<?php
session_start();
include($_SERVER['DOCUMENT_ROOT']."/wall/baba/shiva.php");
include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/user-auth.php");
?>

<?php
$create_post_name  = $login_user;
$create_post_image = "default-user.png";

$userData = mysqli_query($conn, "
    SELECT name, image
    FROM wall_users
    WHERE username='$login_user'
    LIMIT 1
");

if($userData && mysqli_num_rows($userData) > 0){
    $userRow = mysqli_fetch_assoc($userData);

    if(!empty($userRow['name'])){
        $create_post_name = $userRow['name'];
    }

    if(!empty($userRow['image'])){
        $create_post_image = $userRow['image'];
    }
}
error_reporting(E_ALL);
ini_set('display_errors', 1);
  
  
$id = "";
$page_url = "";
$blog_name = "";
$metetitle = "";
$metades = "";
$heading = "";
$image = "";
$short_des = "";
$othur_name = "";
$date = "";
$post_type = "artwork";
$video_url = "";
$youtube_video_id = "";

$poll_id = 0;
$poll_edit_options = [];
$poll_duration = 0;
$poll_ends_at = null;
$poll_total_votes = 0;
$poll_fields_locked = false;


/* Return a valid YouTube video ID or an empty string */
function getYouTubeVideoId($url){

    $url = trim((string)$url);

    if($url === ""){
        return "";
    }

    $parts = parse_url($url);

    if(
        !is_array($parts)
        ||
        empty($parts["host"])
    ){
        return "";
    }

    $host = strtolower(
        preg_replace(
            "/^www\./",
            "",
            (string)$parts["host"]
        )
    );

    $video_id = "";


    /* Standard YouTube link */
    if(
        in_array(
            $host,
            ["youtube.com", "m.youtube.com"],
            true
        )
    ){

        $path = trim(
            (string)($parts["path"] ?? ""),
            "/"
        );

        if($path === "watch"){

            parse_str(
                (string)($parts["query"] ?? ""),
                $query_values
            );

            $video_id = (string)(
                $query_values["v"] ?? ""
            );

        }elseif(
            preg_match(
                "~^(shorts|embed)/([^/?#]+)~",
                $path,
                $matches
            )
        ){

            $video_id = (string)$matches[2];
        }
    }


    /* Short youtu.be link */
    if($host === "youtu.be"){

        $video_id = trim(
            (string)($parts["path"] ?? ""),
            "/"
        );
    }


    if(
        !preg_match(
            "/^[A-Za-z0-9_-]{11}$/",
            $video_id
        )
    ){
        return "";
    }

    return $video_id;
}
  
if(isset($_POST['blog_name'])){

    $edit_id    = isset($_POST['edit_id']) ? trim($_POST['edit_id']) : "";
	    $post_type = trim(
        (string)($_POST['post_type'] ?? 'artwork')
    );

    if(
        !in_array(
            $post_type,
            [
                'artwork',
                'youtube',
                'poll'
            ],
            true
        )
    ){
        $post_type = 'artwork';
    }


    $edit_poll_id = 0;
    $edit_poll_total_votes = 0;
    $edit_poll_title = '';
    $edit_poll_fields_locked = false;
    $edit_poll_images_enabled = false;


    if($edit_id !== ''){

        $validated_edit_id = filter_var(
            $edit_id,
            FILTER_VALIDATE_INT
        );

        if(
            $validated_edit_id === false
            ||
            $validated_edit_id < 1
        ){
            header(
                'Location: /wall/user/user-view-wall.php'
            );

            exit;
        }

        $edit_check_statement = mysqli_prepare(
            $conn,
            "
            SELECT
                HAIWALL.post_type,
                HAIWALL.blog_name,
                wall_polls.id AS poll_id,
                (
                    SELECT COUNT(*)
                    FROM wall_poll_votes
                    WHERE wall_poll_votes.poll_id
                        = wall_polls.id
                ) AS total_votes,
                (
                    SELECT COUNT(*)
                    FROM wall_poll_options
                    WHERE wall_poll_options.poll_id
                        = wall_polls.id
                ) AS total_options,
                (
                    SELECT COUNT(*)
                    FROM wall_poll_options
                    WHERE wall_poll_options.poll_id
                        = wall_polls.id
                      AND wall_poll_options.option_image
                            IS NOT NULL
                      AND wall_poll_options.option_image
                            != ''
                ) AS image_options

            FROM HAIWALL

            LEFT JOIN wall_polls
                ON wall_polls.post_id = HAIWALL.id

            WHERE HAIWALL.id = ?
              AND HAIWALL.post_user = ?

            LIMIT 1
            "
        );

        if(!$edit_check_statement){

            error_log(
                'Unable to prepare edit ownership check'
            );

            http_response_code(500);
            exit('Unable to update post');
        }

        mysqli_stmt_bind_param(
            $edit_check_statement,
            'is',
            $validated_edit_id,
            $login_user
        );

        if(
            !mysqli_stmt_execute(
                $edit_check_statement
            )
        ){

            mysqli_stmt_close(
                $edit_check_statement
            );

            error_log(
                'Unable to execute edit ownership check'
            );

            http_response_code(500);
            exit('Unable to update post');
        }

        $edit_check_result =
            mysqli_stmt_get_result(
                $edit_check_statement
            );

        $edit_check_row =
            mysqli_fetch_assoc(
                $edit_check_result
            );

        mysqli_stmt_close(
            $edit_check_statement
        );


        if(!$edit_check_row){

            header(
                'Location: /wall/user/user-view-wall.php'
            );

            exit;
        }


        $stored_post_type = (string)(
            $edit_check_row['post_type']
            ?? 'artwork'
        );

        if(
            !in_array(
                $stored_post_type,
                [
                    'artwork',
                    'youtube',
                    'poll'
                ],
                true
            )
        ){
            $stored_post_type = 'artwork';
        }

        /*
        Always use the stored post type during edit.
        The submitted value cannot change a post type.
        */
        $post_type = $stored_post_type;


        if($post_type === 'poll'){

            $edit_poll_id = (int)(
                $edit_check_row['poll_id']
                ?? 0
            );

            if($edit_poll_id < 1){

                http_response_code(404);
                exit('Poll data not found');
            }

            $edit_poll_total_votes = (int)(
                $edit_check_row['total_votes']
                ?? 0
            );

            $edit_poll_title = (string)(
                $edit_check_row['blog_name']
                ?? ''
            );

            $edit_poll_fields_locked =
                $edit_poll_total_votes > 0;

            $edit_poll_total_options = (int)(
                $edit_check_row['total_options']
                ?? 0
            );

            $edit_poll_image_options = (int)(
                $edit_check_row['image_options']
                ?? 0
            );

            $edit_poll_images_enabled =
                $edit_poll_total_options > 0
                &&
                $edit_poll_image_options ===
                    $edit_poll_total_options;
        }
    }


    date_default_timezone_set("Asia/Kolkata");
	$poll_options = [];
    $poll_option_source_indexes = [];
    $poll_option_images_enabled = false;
    $poll_option_images = [];
    $poll_option_uploaded_paths = [];
    $poll_option_old_paths_to_delete = [];
    $poll_duration = 0;
    $poll_ends_at = null;

    if($post_type === 'poll'){

        if(!$edit_poll_fields_locked){

            $submitted_options =
                $_POST['poll_options'] ?? [];

        if(!is_array($submitted_options)){
            $submitted_options = [];
        }

        foreach(
            $submitted_options as
            $option_source_index => $option_text
        ){

            $option_text = trim(
                (string)$option_text
            );

            if($option_text === ''){
                continue;
            }

            $option_length = function_exists('mb_strlen')
                ? mb_strlen($option_text, 'UTF-8')
                : strlen($option_text);

            if($option_length > 255){

                header(
                    'Location: create-post.php'
                    . '?add&error=poll_option_too_long'
                );

                exit;
            }

            $poll_options[] = $option_text;

            $poll_option_source_indexes[] =
                (int)$option_source_index;
        }

        if(
            count($poll_options) < 2
            ||
            count($poll_options) > 5
        ){
            header(
                'Location: create-post.php'
                . '?add&error=poll_options'
            );

            exit;
        }

        $submitted_poll_images_enabled =
            isset(
                $_POST[
                    'poll_option_images_enabled'
                ]
            )
            &&
            (string)(
                $_POST[
                    'poll_option_images_enabled'
                ]
            ) === '1';

        if($edit_id !== ''){

            /*
            Existing image polls remain in image mode.
            An imageless poll can enable images before
            it has received any votes.
            */
            $poll_option_images_enabled =
                $edit_poll_images_enabled
                ||
                $submitted_poll_images_enabled;

        }else{

            $poll_option_images_enabled =
                $submitted_poll_images_enabled;
        }

        $normalized_options = [];

        foreach($poll_options as $option_text){

            $normalized_option =
                function_exists('mb_strtolower')
                    ? mb_strtolower(
                        $option_text,
                        'UTF-8'
                    )
                    : strtolower($option_text);

            if(
                in_array(
                    $normalized_option,
                    $normalized_options,
                    true
                )
            ){
                header(
                    'Location: create-post.php'
                    . '?add&error=duplicate_poll_option'
                );

                exit;
            }

            $normalized_options[] =
                $normalized_option;
        }

        $poll_duration = filter_var(
            $_POST['poll_duration'] ?? 0,
            FILTER_VALIDATE_INT
        );

        if(
            $poll_duration === false
            ||
            !in_array(
                $poll_duration,
                [0, 1, 3, 7],
                true
            )
        ){
            header(
                'Location: create-post.php'
                . '?add&error=poll_duration'
            );

            exit;
        }

        if($poll_duration > 0){

            $poll_ends_at = date(
                'Y-m-d H:i:s',
                strtotime(
                    '+' . $poll_duration . ' days'
                )
            );
        }


        if($poll_option_images_enabled){

            $uploaded_option_images =
                $_FILES['poll_option_images']
                ?? [];

            $submitted_option_ids =
                $_POST['poll_option_ids']
                ?? [];

            if(!is_array($submitted_option_ids)){
                $submitted_option_ids = [];
            }

            $poll_image_error_location =
                $edit_id !== ''
                    ? 'create-post.php?id='
                        . rawurlencode($edit_id)
                    : 'create-post.php?add';

            $poll_image_error_separator =
                $edit_id !== ''
                    ? '&'
                    : '&';

            $allowed_option_image_types = [
                'image/jpeg' => 'jpg',
                'image/png' => 'png',
                'image/webp' => 'webp'
            ];

            $option_image_finfo =
                finfo_open(FILEINFO_MIME_TYPE);

            if($option_image_finfo === false){

                http_response_code(500);
                exit('Unable to validate poll images');
            }

            foreach(
                $poll_option_source_indexes as
                $normalized_option_index =>
                    $option_source_index
            ){

                $submitted_option_id = filter_var(
                    $submitted_option_ids[
                        $option_source_index
                    ] ?? 0,
                    FILTER_VALIDATE_INT
                );

                if(
                    $submitted_option_id === false
                    ||
                    $submitted_option_id < 1
                ){
                    $submitted_option_id = 0;
                }

                $upload_error = (int)(
                    $uploaded_option_images['error']
                        [$option_source_index]
                    ?? UPLOAD_ERR_NO_FILE
                );

                if(
                    $upload_error === UPLOAD_ERR_NO_FILE
                    &&
                    $edit_id !== ''
                    &&
                    $submitted_option_id > 0
                ){

                    $poll_option_images[] = [
                        'tmp_name' => '',
                        'extension' => '',
                        'existing_option_id' =>
                            $submitted_option_id,
                        'is_new' => false
                    ];

                    continue;
                }

                $temporary_file = (string)(
                    $uploaded_option_images['tmp_name']
                        [$option_source_index]
                    ?? ''
                );

                $uploaded_size = (int)(
                    $uploaded_option_images['size']
                        [$option_source_index]
                    ?? 0
                );

                if(
                    $upload_error !== UPLOAD_ERR_OK
                    ||
                    $temporary_file === ''
                    ||
                    !is_uploaded_file($temporary_file)
                    ||
                    $uploaded_size < 1
                    ||
                    $uploaded_size > 5242880
                ){

                    finfo_close($option_image_finfo);

                    header(
                        'Location: '
                        . $poll_image_error_location
                        . $poll_image_error_separator
                        . 'error=poll_option_images'
                    );

                    exit;
                }

                $detected_mime = finfo_file(
                    $option_image_finfo,
                    $temporary_file
                );

                $image_dimensions =
                    @getimagesize($temporary_file);

                if(
                    !is_string($detected_mime)
                    ||
                    !isset(
                        $allowed_option_image_types[
                            $detected_mime
                        ]
                    )
                    ||
                    $image_dimensions === false
                ){

                    finfo_close($option_image_finfo);

                    header(
                        'Location: '
                        . $poll_image_error_location
                        . $poll_image_error_separator
                        . 'error=invalid_poll_option_image'
                    );

                    exit;
                }

                $poll_option_images[] = [
                    'tmp_name' => $temporary_file,
                    'extension' =>
                        $allowed_option_image_types[
                            $detected_mime
                        ],
                    'existing_option_id' =>
                        $submitted_option_id,
                    'is_new' => true
                ];
            }

            finfo_close($option_image_finfo);

            if(
                count($poll_option_images)
                !==
                count($poll_options)
            ){

                header(
                    'Location: '
                    . $poll_image_error_location
                    . $poll_image_error_separator
                    . 'error=poll_option_images'
                );

                exit;
            }
        }

        }
    }

    $video_url = trim(
        (string)($_POST['video_url'] ?? '')
    );

    $youtube_video_id = '';

    if($post_type === 'youtube'){

        $youtube_video_id =
            getYouTubeVideoId($video_url);

        if($youtube_video_id === ''){

            header(
                "Location: create-post.php"
                . "?add&error=invalid_youtube_url"
            );

            exit;
        }

        /*
        Store a clean canonical URL instead of
        saving unnecessary tracking parameters.
        */
        $video_url =
            'https://www.youtube.com/watch?v='
            . $youtube_video_id;

    }else{

        $video_url = '';
        $youtube_video_id = '';
    }
    $submitted_blog_name = trim(
        (string)($_POST['blog_name'] ?? '')
    );

    if(
        $post_type === 'poll'
        &&
        $edit_poll_fields_locked
    ){
        $submitted_blog_name =
            $edit_poll_title;
    }

    $blog_name = mysqli_real_escape_string(
        $conn,
        $submitted_blog_name
    );
	$slug = strtolower($blog_name);
	$slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
	$slug = trim($slug, '-');
	$slug = $slug . '-' . time(); 

	$metetitle  = mysqli_real_escape_string($conn, trim($_POST['metetitle']));
	$metades    = mysqli_real_escape_string($conn, trim($_POST['metades']));
	$heading    = mysqli_real_escape_string($conn, trim($_POST['heading']));
	$short_des  = mysqli_real_escape_string($conn, trim($_POST['short_des']));
	$othur_name = mysqli_real_escape_string($conn, trim($_POST['othur_name']));
    if($metetitle == ""){
        $metetitle = $blog_name;
    }

    if($metades == ""){
        $metades = $short_des;
    }

    if($othur_name == ""){
        if($heading != ""){
            $othur_name = $blog_name . ", " . $heading;
        }else{
            $othur_name = $blog_name;
        }
    }

    $metetitle  = mb_substr($metetitle, 0, 100);
    $metades    = mb_substr($metades, 0, 200);
    $othur_name = mb_substr($othur_name, 0, 200);

    $date = date("Y-m-d H:i:s");

    if(empty($edit_id)){

        // CREATE MODE
        $imageFileName = "";

        if($post_type === "artwork"){

            if(!empty($_POST['croppedImage'])){

                $imageData = (string)$_POST['croppedImage'];

                $imageData = str_replace(
                    'data:image/jpeg;base64,',
                    '',
                    $imageData
                );

                $imageData = str_replace(
                    ' ',
                    '+',
                    $imageData
                );

                $decodedImage = base64_decode(
                    $imageData,
                    true
                );

                if($decodedImage === false){

                    header(
                        "Location: create-post.php"
                        . "?add&error=invalid_image"
                    );

                    exit;
                }

                $imageFileName =
                    time()
                    . "_"
                    . rand(1000, 9999)
                    . ".jpg";

                $targetFolder =
                    $_SERVER['DOCUMENT_ROOT']
                    . "/wall/wall-feeds/";

                $imageSaved = file_put_contents(
                    $targetFolder . $imageFileName,
                    $decodedImage
                );

                if($imageSaved === false){

                    header(
                        "Location: create-post.php"
                        . "?add&error=image_save"
                    );

                    exit;
                }
            }

            if($imageFileName === ""){

                header(
                    "Location: create-post.php"
                    . "?add&error=image"
                );

                exit;
            }

        }elseif($post_type === "youtube"){

            /*
            Store the YouTube thumbnail URL.
            No video file is stored on HAI Wall.
            */
            $imageFileName =
                "https://i.ytimg.com/vi/"
                . $youtube_video_id
                . "/hqdefault.jpg";

        }else{

            /* Poll posts do not require a main post image */
            $imageFileName = "";
        }


        if(
            $post_type === 'poll'
            &&
            $poll_option_images_enabled
        ){

            $poll_option_target_folder =
                $_SERVER['DOCUMENT_ROOT']
                . '/wall/wall-feeds/polls/';

            foreach(
                $poll_option_images as
                $option_image_index => $option_image
            ){

                try{

                    $option_image_file_name =
                        'poll_option_'
                        . bin2hex(random_bytes(12))
                        . '.'
                        . $option_image['extension'];

                }catch(Throwable $error){

                    foreach(
                        $poll_option_uploaded_paths as
                        $uploaded_option_path
                    ){
                        if(is_file($uploaded_option_path)){
                            @unlink($uploaded_option_path);
                        }
                    }

                    throw $error;
                }

                $option_image_target_path =
                    $poll_option_target_folder
                    . $option_image_file_name;

                if(
                    !move_uploaded_file(
                        $option_image['tmp_name'],
                        $option_image_target_path
                    )
                ){

                    foreach(
                        $poll_option_uploaded_paths as
                        $uploaded_option_path
                    ){
                        if(is_file($uploaded_option_path)){
                            @unlink($uploaded_option_path);
                        }
                    }

                    header(
                        'Location: create-post.php'
                        . '?add&error=poll_option_image_save'
                    );

                    exit;
                }

                $poll_option_images[
                    $option_image_index
                ]['file_name'] =
                    $option_image_file_name;

                $poll_option_uploaded_paths[] =
                    $option_image_target_path;
            }
        }

        $safe_post_type = mysqli_real_escape_string(
            $conn,
            $post_type
        );

        $safe_video_url = mysqli_real_escape_string(
            $conn,
            $video_url
        );

        $safe_youtube_video_id =
            mysqli_real_escape_string(
                $conn,
                $youtube_video_id
            );

        $insert = "INSERT INTO HAIWALL
        (
            page_url,
            blog_name,
            metetitle,
            metades,
            heading,
            image,
            short_des,
            othur_name,
            date,
            post_user,
            status,
            post_type,
            video_url,
            youtube_video_id
        )
        VALUES
        (
            '$slug',
            '$blog_name',
            '$metetitle',
            '$metades',
            '$heading',
            '$imageFileName',
            '$short_des',
            '$othur_name',
            '$date',
            '$login_user',
            '1',
            '$safe_post_type',
            '$safe_video_url',
            '$safe_youtube_video_id'
        )";
		
mysqli_begin_transaction($conn);

try {

    if(!mysqli_query($conn, $insert)){
        throw new Exception(
            "Post insert failed: "
            . mysqli_error($conn)
        );
    }

    $last_id = mysqli_insert_id($conn);
    $final_url = $slug . "-" . $last_id;

    $update_url = mysqli_prepare(
        $conn,
        "
        UPDATE HAIWALL
        SET page_url = ?
        WHERE id = ?
        LIMIT 1
        "
    );

    if(!$update_url){
        throw new Exception(
            "Post URL preparation failed"
        );
    }

    mysqli_stmt_bind_param(
        $update_url,
        "si",
        $final_url,
        $last_id
    );

    if(!mysqli_stmt_execute($update_url)){
        mysqli_stmt_close($update_url);

        throw new Exception(
            "Post URL update failed"
        );
    }

    mysqli_stmt_close($update_url);


    if($post_type === "poll"){

        $insert_poll = mysqli_prepare(
            $conn,
            "
            INSERT INTO wall_polls
            (
                post_id,
                ends_at
            )
            VALUES (?, ?)
            "
        );

        if(!$insert_poll){
            throw new Exception(
                "Poll preparation failed"
            );
        }

        mysqli_stmt_bind_param(
            $insert_poll,
            "is",
            $last_id,
            $poll_ends_at
        );

        if(!mysqli_stmt_execute($insert_poll)){
            mysqli_stmt_close($insert_poll);

            throw new Exception(
                "Poll insert failed"
            );
        }

        $poll_id = mysqli_insert_id($conn);

        mysqli_stmt_close($insert_poll);


        $insert_option = mysqli_prepare(
            $conn,
            "
            INSERT INTO wall_poll_options
            (
                poll_id,
                option_text,
                option_image,
                display_order
            )
            VALUES (?, ?, ?, ?)
            "
        );

        if(!$insert_option){
            throw new Exception(
                "Poll option preparation failed"
            );
        }

        foreach(
            $poll_options as
            $option_index => $option_text
        ){

            $display_order = $option_index + 1;

            $option_image_name =
                $poll_option_images_enabled
                    ? (
                        $poll_option_images[
                            $option_index
                        ]['file_name']
                        ?? null
                    )
                    : null;

            mysqli_stmt_bind_param(
                $insert_option,
                "issi",
                $poll_id,
                $option_text,
                $option_image_name,
                $display_order
            );

            if(!mysqli_stmt_execute($insert_option)){
                mysqli_stmt_close($insert_option);

                throw new Exception(
                    "Poll option insert failed"
                );
            }
        }

        mysqli_stmt_close($insert_option);
    }


    $first_post_update = mysqli_prepare(
        $conn,
        "
        UPDATE wall_users
        SET first_post_done = 1
        WHERE username = ?
        LIMIT 1
        "
    );

    if(!$first_post_update){
        throw new Exception(
            "User update preparation failed"
        );
    }

    mysqli_stmt_bind_param(
        $first_post_update,
        "s",
        $login_user
    );

    if(!mysqli_stmt_execute($first_post_update)){
        mysqli_stmt_close($first_post_update);

        throw new Exception(
            "User update failed"
        );
    }

    mysqli_stmt_close($first_post_update);

    mysqli_commit($conn);

    header(
        "Location: /wall/user/user-view-wall.php"
    );

    exit;

} catch(Throwable $error){

    mysqli_rollback($conn);

    foreach(
        $poll_option_uploaded_paths as
        $uploaded_option_path
    ){
        if(is_file($uploaded_option_path)){
            @unlink($uploaded_option_path);
        }
    }

    error_log(
        "HAI Wall post creation failed: "
        . $error->getMessage()
    );

    http_response_code(500);

    exit("Unable to create post");
}
    }else{

        // EDIT MODE
        $edit_id = mysqli_real_escape_string($conn, $edit_id);

        $checkPost = mysqli_query($conn, "
            SELECT image FROM HAIWALL
            WHERE id='$edit_id' AND post_user='$login_user'
            LIMIT 1
        ");

        if(!$checkPost || mysqli_num_rows($checkPost) == 0){
            header("Location: /wall/user/user-view-wall.php");
            exit;
        }

    $update = "UPDATE HAIWALL SET
    blog_name='$blog_name',
    metetitle='$metetitle',
    metades='$metades',
    heading='$heading',
    short_des='$short_des',
    othur_name='$othur_name'
    WHERE id='$edit_id' AND post_user='$login_user'
    LIMIT 1";

        mysqli_begin_transaction($conn);

        try {

            if(!mysqli_query($conn, $update)){

                throw new Exception(
                    'Post update failed: '
                    . mysqli_error($conn)
                );
            }


            if(
                $post_type === 'poll'
                &&
                !$edit_poll_fields_locked
            ){

                $update_poll_statement =
                    mysqli_prepare(
                        $conn,
                        "
                        UPDATE wall_polls
                        SET ends_at = ?
                        WHERE id = ?
                        LIMIT 1
                        "
                    );

                if(!$update_poll_statement){

                    throw new Exception(
                        'Poll update preparation failed'
                    );
                }

                mysqli_stmt_bind_param(
                    $update_poll_statement,
                    'si',
                    $poll_ends_at,
                    $edit_poll_id
                );

                if(
                    !mysqli_stmt_execute(
                        $update_poll_statement
                    )
                ){

                    mysqli_stmt_close(
                        $update_poll_statement
                    );

                    throw new Exception(
                        'Poll duration update failed'
                    );
                }

                mysqli_stmt_close(
                    $update_poll_statement
                );


                $existing_option_images = [];
                $existing_option_images_by_id = [];

                $existing_images_statement =
                    mysqli_prepare(
                        $conn,
                        "
                        SELECT
                            id,
                            option_image
                        FROM wall_poll_options
                        WHERE poll_id = ?
                        ORDER BY
                            display_order ASC,
                            id ASC
                        "
                    );

                if(!$existing_images_statement){

                    throw new Exception(
                        'Existing poll images preparation failed'
                    );
                }

                mysqli_stmt_bind_param(
                    $existing_images_statement,
                    'i',
                    $edit_poll_id
                );

                if(
                    !mysqli_stmt_execute(
                        $existing_images_statement
                    )
                ){

                    mysqli_stmt_close(
                        $existing_images_statement
                    );

                    throw new Exception(
                        'Existing poll images load failed'
                    );
                }

                $existing_images_result =
                    mysqli_stmt_get_result(
                        $existing_images_statement
                    );

                while(
                    $existing_image_row =
                        mysqli_fetch_assoc(
                            $existing_images_result
                        )
                ){

                    $existing_option_id = (int)(
                        $existing_image_row['id']
                        ?? 0
                    );

                    $existing_image_name =
                        !empty(
                            $existing_image_row[
                                'option_image'
                            ]
                        )
                            ? basename(
                                (string)$existing_image_row[
                                    'option_image'
                                ]
                            )
                            : null;

                    $existing_option_images[] =
                        $existing_image_name;

                    if($existing_option_id > 0){

                        $existing_option_images_by_id[
                            $existing_option_id
                        ] = $existing_image_name;
                    }
                }

                mysqli_stmt_close(
                    $existing_images_statement
                );


                $delete_options_statement =
                    mysqli_prepare(
                        $conn,
                        "
                        DELETE FROM wall_poll_options
                        WHERE poll_id = ?
                        "
                    );

                if(!$delete_options_statement){

                    throw new Exception(
                        'Poll option delete preparation failed'
                    );
                }

                mysqli_stmt_bind_param(
                    $delete_options_statement,
                    'i',
                    $edit_poll_id
                );

                if(
                    !mysqli_stmt_execute(
                        $delete_options_statement
                    )
                ){

                    mysqli_stmt_close(
                        $delete_options_statement
                    );

                    throw new Exception(
                        'Existing poll options delete failed'
                    );
                }

                mysqli_stmt_close(
                    $delete_options_statement
                );


                $insert_edit_option_statement =
                    mysqli_prepare(
                        $conn,
                        "
                        INSERT INTO wall_poll_options
                        (
                            poll_id,
                            option_text,
                            option_image,
                            display_order
                        )
                        VALUES (?, ?, ?, ?)
                        "
                    );

                if(!$insert_edit_option_statement){

                    throw new Exception(
                        'Poll option update preparation failed'
                    );
                }

                $poll_option_target_folder =
                    $_SERVER['DOCUMENT_ROOT']
                    . '/wall/wall-feeds/polls/';

                if(
                    $poll_option_images_enabled
                    &&
                    !is_dir($poll_option_target_folder)
                ){

                    throw new Exception(
                        'Poll image folder not found'
                    );
                }

                $retained_existing_option_ids = [];

                foreach(
                    $poll_options as
                    $option_index => $option_text
                ){

                    $display_order =
                        $option_index + 1;

                    $option_image_data =
                        $poll_option_images[
                            $option_index
                        ]
                        ?? null;

                    $existing_option_id = (int)(
                        $option_image_data[
                            'existing_option_id'
                        ]
                        ?? 0
                    );

                    if(
                        $existing_option_id > 0
                        &&
                        !array_key_exists(
                            $existing_option_id,
                            $existing_option_images_by_id
                        )
                    ){

                        throw new Exception(
                            'Invalid existing poll option'
                        );
                    }

                    $option_image_name =
                        $existing_option_id > 0
                            ? (
                                $existing_option_images_by_id[
                                    $existing_option_id
                                ]
                                ?? null
                            )
                            : null;

                    if($existing_option_id > 0){

                        $retained_existing_option_ids[] =
                            $existing_option_id;
                    }

                    $has_new_option_image =
                        is_array($option_image_data)
                        &&
                        !empty(
                            $option_image_data['is_new']
                        );

                    if($has_new_option_image){

                        $new_option_image_name =
                            'poll_option_'
                            . bin2hex(random_bytes(12))
                            . '.'
                            . $option_image_data[
                                'extension'
                            ];

                        $new_option_image_path =
                            $poll_option_target_folder
                            . $new_option_image_name;

                        if(
                            !move_uploaded_file(
                                $option_image_data[
                                    'tmp_name'
                                ],
                                $new_option_image_path
                            )
                        ){

                            throw new Exception(
                                'Poll option image save failed'
                            );
                        }

                        $poll_option_uploaded_paths[] =
                            $new_option_image_path;

                        if(
                            $option_image_name !== null
                            &&
                            $option_image_name !== ''
                        ){

                            $poll_option_old_paths_to_delete[] =
                                $poll_option_target_folder
                                . basename(
                                    $option_image_name
                                );
                        }

                        $option_image_name =
                            $new_option_image_name;
                    }

                    if(
                        $poll_option_images_enabled
                        &&
                        (
                            $option_image_name === null
                            ||
                            $option_image_name === ''
                        )
                    ){

                        throw new Exception(
                            'Poll option image is required'
                        );
                    }

                    mysqli_stmt_bind_param(
                        $insert_edit_option_statement,
                        'issi',
                        $edit_poll_id,
                        $option_text,
                        $option_image_name,
                        $display_order
                    );

                    if(
                        !mysqli_stmt_execute(
                            $insert_edit_option_statement
                        )
                    ){

                        mysqli_stmt_close(
                            $insert_edit_option_statement
                        );

                        throw new Exception(
                            'Poll option update failed'
                        );
                    }
                }

                foreach(
                    $existing_option_images_by_id as
                    $existing_option_id =>
                        $existing_option_image_name
                ){

                    if(
                        in_array(
                            (int)$existing_option_id,
                            $retained_existing_option_ids,
                            true
                        )
                        ||
                        empty($existing_option_image_name)
                    ){
                        continue;
                    }

                    $poll_option_old_paths_to_delete[] =
                        $poll_option_target_folder
                        . basename(
                            $existing_option_image_name
                        );
                }

                mysqli_stmt_close(
                    $insert_edit_option_statement
                );
            }


            mysqli_commit($conn);

            foreach(
                array_unique(
                    $poll_option_old_paths_to_delete
                ) as $old_option_image_path
            ){

                if(is_file($old_option_image_path)){
                    @unlink($old_option_image_path);
                }
            }

            header(
                'Location: /wall/user/user-view-wall.php'
            );

            exit;

        } catch(Throwable $error){

            mysqli_rollback($conn);

            foreach(
                $poll_option_uploaded_paths as
                $uploaded_option_path
            ){

                if(is_file($uploaded_option_path)){
                    @unlink($uploaded_option_path);
                }
            }

            error_log(
                'HAI Wall post update failed: '
                . $error->getMessage()
            );

            http_response_code(500);
            exit('Unable to update post');
        }
    }
}
	
 

if(isset($_GET['id']) && !empty($_GET['id'])){

    $up_id = mysqli_real_escape_string($conn, $_GET['id']);

    $update_select = mysqli_query($conn, "
        SELECT * FROM HAIWALL
        WHERE id='$up_id' AND post_user='$login_user'
        LIMIT 1
    ");

    if($update_select && mysqli_num_rows($update_select) > 0){

        $row = mysqli_fetch_assoc($update_select);

        $id         = $row['id'];
        $page_url   = $row['page_url'];
        $blog_name  = $row['blog_name'];
        $metetitle  = $row['metetitle'];
        $metades    = $row['metades'];
        $heading    = $row['heading'];
        $image      = $row['image'];
        $short_des  = $row['short_des'];
        $othur_name      = $row['othur_name'];
        $date            = $row['date'];
        $post_type       = !empty($row['post_type'])
            ? $row['post_type']
            : 'artwork';
        $video_url       = (string)($row['video_url'] ?? '');
        $youtube_video_id = (string)(
            $row['youtube_video_id'] ?? ''
        );


        if($post_type === 'poll'){

            $poll_statement = mysqli_prepare(
                $conn,
                "
                SELECT
                    wall_polls.id,
                    wall_polls.ends_at,
                    wall_polls.created_at,
                    (
                        SELECT COUNT(*)
                        FROM wall_poll_votes
                        WHERE wall_poll_votes.poll_id
                            = wall_polls.id
                    ) AS total_votes

                FROM wall_polls

                WHERE wall_polls.post_id = ?

                LIMIT 1
                "
            );

            if(!$poll_statement){

                error_log(
                    'Unable to prepare poll edit data'
                );

                http_response_code(500);
                exit('Unable to load poll');
            }

            $edit_post_id = (int)$id;

            mysqli_stmt_bind_param(
                $poll_statement,
                'i',
                $edit_post_id
            );

            if(!mysqli_stmt_execute($poll_statement)){

                mysqli_stmt_close($poll_statement);

                error_log(
                    'Unable to execute poll edit data'
                );

                http_response_code(500);
                exit('Unable to load poll');
            }

            $poll_result =
                mysqli_stmt_get_result(
                    $poll_statement
                );

            $poll_row = mysqli_fetch_assoc(
                $poll_result
            );

            mysqli_stmt_close($poll_statement);


            if(!$poll_row){

                http_response_code(404);
                exit('Poll data not found');
            }

            $poll_id = (int)$poll_row['id'];

            $poll_ends_at =
                $poll_row['ends_at'] !== null
                    ? (string)$poll_row['ends_at']
                    : null;

            $poll_total_votes = (int)(
                $poll_row['total_votes'] ?? 0
            );

            $poll_fields_locked =
                $poll_total_votes > 0;


            if($poll_ends_at !== null){

                $poll_created_time = strtotime(
                    (string)$poll_row['created_at']
                );

                $poll_end_time = strtotime(
                    $poll_ends_at
                );

                if(
                    $poll_created_time !== false
                    &&
                    $poll_end_time !== false
                ){

                    $poll_duration = (int)round(
                        (
                            $poll_end_time
                            -
                            $poll_created_time
                        )
                        /
                        86400
                    );
                }

                if(
                    !in_array(
                        $poll_duration,
                        [1, 3, 7],
                        true
                    )
                ){
                    $poll_duration = 0;
                }
            }


            $option_statement = mysqli_prepare(
                $conn,
                "
                SELECT
                    id,
                    option_text,
                    option_image,
                    display_order

                FROM wall_poll_options

                WHERE poll_id = ?

                ORDER BY
                    display_order ASC,
                    id ASC
                "
            );

            if(!$option_statement){

                error_log(
                    'Unable to prepare poll options'
                );

                http_response_code(500);
                exit('Unable to load poll options');
            }

            mysqli_stmt_bind_param(
                $option_statement,
                'i',
                $poll_id
            );

            if(!mysqli_stmt_execute($option_statement)){

                mysqli_stmt_close($option_statement);

                error_log(
                    'Unable to execute poll options'
                );

                http_response_code(500);
                exit('Unable to load poll options');
            }

            $option_result =
                mysqli_stmt_get_result(
                    $option_statement
                );

            while(
                $option_row =
                    mysqli_fetch_assoc($option_result)
            ){

                $poll_edit_options[] = [
                    'id' => (int)$option_row['id'],
                    'option_text' => (string)(
                        $option_row['option_text']
                        ?? ''
                    ),
                    'option_image' => !empty(
                        $option_row['option_image']
                    )
                        ? basename(
                            (string)$option_row[
                                'option_image'
                            ]
                        )
                        : '',
                    'display_order' => (int)(
                        $option_row['display_order']
                        ?? 0
                    )
                ];
            }

            mysqli_stmt_close($option_statement);
        }

    }else{
        header("Location: user-view-wall.php");
        exit;
    }
}
 
 
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Create Post | HAI WALL</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="../../codes/glry/js/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="shortcut icon" href="https://www.himanshuartinstitute.com/wall/bcknds/hai-wall.png" type="image/x-icon" >
<link href="../bcknds/css/wall-home.css?v=20260722-5" media="screen" rel="stylesheet" type="text/css" />
<link href="../bcknds/css/create-post.css?v=20260803-1" media="screen" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css">
</head>

<body>

<!-- HEADER -->
<?php include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/header.php"); ?>


<!-- MAIN -->
<div class="container">

<!-- LEFT SIDEBAR -->
<div class="sidebar leftcolmn">
<!-- TOP LIKED POST -->
<?php include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/top-liked-post.php"); ?>
<!-- NEW USER SLIDER -->
<?php include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/new-users.php"); ?>
</div>








<!-- CENTER WALL -->
<?php if(isset($_GET['add']) || !empty($id)){ ?>
<div class="haifeed-colum">
  <div class="wall-container">


<div class="post-create-wrap">
  <div class="post-create-card">

    <div class="post-create-head">
      <div class="post-create-user">
        <img src="/wall/user/user-images/<?php echo htmlspecialchars($create_post_image); ?>" alt="<?php echo htmlspecialchars($create_post_name); ?>">
        <div>
           <h2><?=!empty($id) ? 'Edit Post' : 'Create Post'?></h2>
			<p><?=!empty($id) ? 'Update Your Post Details' : 'Posting as ' . htmlspecialchars($create_post_name)?></p> 
        </div>
      </div>
    </div>

    <form
        method="POST"
        enctype="multipart/form-data"
        class="post-create-form"
        id="postForm"
    >

    <input
        type="hidden"
        name="edit_id"
        value="<?=htmlspecialchars(
            $id,
            ENT_QUOTES,
            'UTF-8'
        )?>"
    >


<?php if(empty($id)){ ?>

<div class="post-type-section">

    <div class="post-type-heading">
        What would you like to share?
    </div>

<div class="post-type-options">

    <label class="post-type-option is-active">

        <input
            type="radio"
            name="post_type"
            value="artwork"
            checked
        >

        <i
            class="fa fa-image"
            aria-hidden="true"
        ></i>

        <span>Artwork</span>

    </label>

    <label class="post-type-option">

        <input
            type="radio"
            name="post_type"
            value="youtube"
        >

        <i
            class="fa fa-youtube-play"
            aria-hidden="true"
        ></i>

        <span>YouTube Video</span>

    </label>

    <label class="post-type-option">

        <input
            type="radio"
            name="post_type"
            value="poll"
        >

        <i
            class="fa fa-bar-chart"
            aria-hidden="true"
        ></i>

        <span>Poll</span>

    </label>

</div>
</div>


<div id="artworkPostFields">

    <div class="pc-field">

        <label>Post Image</label>

        <div class="upload-box" id="uploadBox">

            <input
                type="file"
                name="image"
                id="imageInput"
                accept="image/jpeg,image/png,image/webp"
            >

            <div class="upload-box-inner">

                <i
                    class="fa fa-camera"
                    aria-hidden="true"
                ></i>

                <h4>Tap to upload image</h4>

                <p>JPG, PNG and WebP supported</p>

            </div>

        </div>

        <input
            type="hidden"
            name="croppedImage"
            id="croppedImage"
        >

        <div
            class="preview-card"
            id="previewCard"
            style="display:none;"
        >

            <img
                id="previewImage"
                src=""
                alt="Artwork preview"
            >

            <button
                type="button"
                class="change-img-btn"
                id="changeImageBtn"
            >
                Change Image
            </button>

        </div>

    </div>

</div>


<div
    id="youtubePostFields"
    style="display:none;"
>

    <div class="pc-field">

        <label for="youtubeUrlInput">
            YouTube Video Link
        </label>

        <input
            type="url"
            name="video_url"
            id="youtubeUrlInput"
            placeholder="Paste YouTube video or Shorts link"
            autocomplete="url"
        >

        <p class="pc-field-help">
            YouTube, YouTube Shorts and youtu.be links are supported.
        </p>

    </div>

    <div
        class="youtube-preview-card"
        id="youtubePreviewCard"
        style="display:none;"
    >

        <div class="youtube-preview-image">

            <img
                src=""
                id="youtubePreviewImage"
                alt="YouTube video preview"
            >

            <span class="youtube-play-icon">

                <i
                    class="fa fa-play"
                    aria-hidden="true"
                ></i>

            </span>

        </div>

        <div
            class="youtube-preview-message"
            id="youtubePreviewMessage"
        >
            YouTube video preview
        </div>

    </div>

</div>



<div
    id="pollPostFields"
    style="display:none;"
>

    <div class="pc-field">

        <label>Poll Options</label>

        <label
            class="poll-option-images-toggle"
            for="pollOptionImagesEnabled"
        >
            <input
                type="checkbox"
                name="poll_option_images_enabled"
                id="pollOptionImagesEnabled"
                value="1"
            >

            <span>
                Add an image to every poll option
            </span>
        </label>

        <p class="pc-field-help">
            If enabled, an image is required for every option.
        </p>

        <div id="pollOptionsList">

            <div class="poll-option-row">

                <input
                    type="text"
                    name="poll_options[]"
                    class="poll-option-input"
                    maxlength="255"
                    placeholder="Option 1"
                >

                <div
                    class="poll-option-image-field"
                    hidden
                >
                    <label class="poll-option-image-picker">

                        <input
                            type="file"
                            name="poll_option_images[]"
                            class="poll-option-image-input"
                            accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
                            aria-label="Add image for option 1"
                        >

                        <span class="poll-option-image-placeholder">

                            <i
                                class="fa fa-camera"
                                aria-hidden="true"
                            ></i>

                            <span>Add Image</span>

                        </span>

                        <img
                            class="poll-option-image-preview"
                            src=""
                            alt="Cropped preview for option 1"
                            hidden
                        >

                        <span
                            class="poll-option-image-change"
                            aria-hidden="true"
                            hidden
                        >
                            <i class="fa fa-camera"></i>
                        </span>

                    </label>
                </div>

            </div>

            <div class="poll-option-row">

                <input
                    type="text"
                    name="poll_options[]"
                    class="poll-option-input"
                    maxlength="255"
                    placeholder="Option 2"
                >

                <div
                    class="poll-option-image-field"
                    hidden
                >
                    <label class="poll-option-image-picker">

                        <input
                            type="file"
                            name="poll_option_images[]"
                            class="poll-option-image-input"
                            accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
                            aria-label="Add image for option 2"
                        >

                        <span class="poll-option-image-placeholder">

                            <i
                                class="fa fa-camera"
                                aria-hidden="true"
                            ></i>

                            <span>Add Image</span>

                        </span>

                        <img
                            class="poll-option-image-preview"
                            src=""
                            alt="Cropped preview for option 2"
                            hidden
                        >

                        <span
                            class="poll-option-image-change"
                            aria-hidden="true"
                            hidden
                        >
                            <i class="fa fa-camera"></i>
                        </span>

                    </label>
                </div>

            </div>

        </div>

        <button
            type="button"
            id="addPollOption"
            class="add-poll-option-btn"
        >
            <i
                class="fa fa-plus"
                aria-hidden="true"
            ></i>
            Add Option
        </button>

        <p class="pc-field-help">
            Add between 2 and 5 options.
        </p>

    </div>

    <div class="pc-field">

        <label for="pollDuration">
            Poll Duration
        </label>

        <select
            name="poll_duration"
            id="pollDuration"
        >
            <option value="1">1 Day</option>
            <option value="3">3 Days</option>
            <option value="7">7 Days</option>
            <option value="0">No End Date</option>
        </select>

    </div>

</div>
<?php }else{ ?>

<input
    type="hidden"
    name="post_type"
    value="<?=htmlspecialchars(
        $post_type,
        ENT_QUOTES,
        'UTF-8'
    )?>"
>

<?php if($post_type === 'youtube'){ ?>

<div class="pc-field">

    <label for="youtubeUrlInput">
        YouTube Video Link
    </label>

    <input
        type="url"
        name="video_url"
        id="youtubeUrlInput"
        value="<?=htmlspecialchars(
            $video_url,
            ENT_QUOTES,
            'UTF-8'
        )?>"
        required
    >

</div>

<?php }elseif($post_type === 'poll'){ ?>

<?php

$poll_edit_image_count = 0;

foreach($poll_edit_options as $poll_edit_option){

    if(
        !empty(
            trim(
                (string)(
                    $poll_edit_option['option_image']
                    ?? ''
                )
            )
        )
    ){
        $poll_edit_image_count++;
    }
}

$poll_edit_images_enabled =
    count($poll_edit_options) > 0
    &&
    $poll_edit_image_count ===
        count($poll_edit_options);

?>

<div id="pollPostFields">

    <?php if($poll_fields_locked){ ?>

    <div class="poll-edit-notice">

        <i
            class="fa fa-lock"
            aria-hidden="true"
        ></i>

        <span>
            This poll has received votes. Its title,
            options and duration can no longer be changed.
        </span>

    </div>

    <?php } ?>

    <div class="pc-field">

        <label>Poll Options</label>

        <?php if(!$poll_fields_locked){ ?>

        <label
            class="poll-option-images-toggle"
            for="pollOptionImagesEnabled"
        >
            <input
                type="checkbox"
                name="poll_option_images_enabled"
                id="pollOptionImagesEnabled"
                value="1"
                <?=!empty($poll_edit_images_enabled)
                    ? 'checked disabled'
                    : ''
                ?>
            >

            <span>
                Add an image to every poll option
            </span>
        </label>

        <p class="pc-field-help">
            If enabled, an image is required for every option.
        </p>

        <?php } ?>

        <div id="pollOptionsList">

            <?php foreach(
                $poll_edit_options as
                $option_index => $poll_option
            ){ ?>

            <div class="poll-option-row">

                <?php

                $edit_option_image = trim(
                    (string)(
                        $poll_option['option_image']
                        ?? ''
                    )
                );

                $edit_option_image_url =
                    $edit_option_image !== ''
                        ? '/wall/wall-feeds/polls/'
                            . rawurlencode(
                                $edit_option_image
                            )
                        : '';

                ?>

                <input
                    type="hidden"
                    name="poll_option_ids[]"
                    value="<?=(int)(
                        $poll_option['id'] ?? 0
                    )?>"
                >

                <input
                    type="hidden"
                    name="existing_poll_option_images[]"
                    value="<?=htmlspecialchars(
                        $edit_option_image,
                        ENT_QUOTES,
                        'UTF-8'
                    )?>"
                >

                <?php if(
                    !$poll_fields_locked
                    ||
                    $edit_option_image_url !== ''
                ){ ?>

                <div
                    class="poll-option-image-field"
                    <?=$edit_option_image_url === ''
                        ? 'hidden'
                        : ''
                    ?>
                >

                    <?php if(!$poll_fields_locked){ ?>

                    <label class="poll-option-image-picker">

                        <input
                            type="file"
                            name="poll_option_images[]"
                            class="poll-option-image-input"
                            accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp"
                            aria-label="Add or change image for option <?=($option_index + 1)?>"
                            data-existing-image="<?=$edit_option_image_url !== ''
                                ? '1'
                                : '0'
                            ?>"
                        >

                        <span
                            class="poll-option-image-placeholder"
                            <?=$edit_option_image_url !== ''
                                ? 'hidden'
                                : ''
                            ?>
                        >

                            <i
                                class="fa fa-camera"
                                aria-hidden="true"
                            ></i>

                            <span>Add Image</span>

                        </span>

                        <img
                            class="poll-option-image-preview"
                            src="<?=htmlspecialchars(
                                $edit_option_image_url,
                                ENT_QUOTES,
                                'UTF-8'
                            )?>"
                            alt="Image for option <?=($option_index + 1)?>"
                            loading="lazy"
                            decoding="async"
                            <?=$edit_option_image_url === ''
                                ? 'hidden'
                                : ''
                            ?>
                        >

                        <span
                            class="poll-option-image-change"
                            aria-hidden="true"
                            <?=$edit_option_image_url === ''
                                ? 'hidden'
                                : ''
                            ?>
                        >
                            <i class="fa fa-camera"></i>
                        </span>

                    </label>

                    <?php }else{ ?>

                    <span class="poll-option-image-picker">

                        <img
                            class="poll-option-image-preview"
                            src="<?=htmlspecialchars(
                                $edit_option_image_url,
                                ENT_QUOTES,
                                'UTF-8'
                            )?>"
                            alt="Current image for option <?=($option_index + 1)?>"
                            loading="lazy"
                            decoding="async"
                        >

                    </span>

                    <?php } ?>

                </div>

                <?php } ?>

                <input
                    type="text"
                    name="poll_options[]"
                    class="poll-option-input"
                    maxlength="255"
                    placeholder="Option <?=($option_index + 1)?>"
                    value="<?=htmlspecialchars(
                        $poll_option['option_text'],
                        ENT_QUOTES,
                        'UTF-8'
                    )?>"
                    <?=$poll_fields_locked
                        ? 'readonly'
                        : ''
                    ?>
                >

                <?php if(!$poll_fields_locked){ ?>

                <button
                    type="button"
                    class="remove-poll-option"
                    aria-label="Remove poll option"
                    title="Remove option"
                >
                    <i
                        class="fa fa-times"
                        aria-hidden="true"
                    ></i>
                </button>

                <?php } ?>

            </div>

            <?php } ?>

        </div>

        <?php if(!$poll_fields_locked){ ?>

        <button
            type="button"
            id="addPollOption"
            class="add-poll-option-btn"
        >
            <i
                class="fa fa-plus"
                aria-hidden="true"
            ></i>

            Add Option
        </button>

        <p class="pc-field-help">
            Add between 2 and 5 options.
        </p>

        <?php } ?>

    </div>

    <div class="pc-field">

        <label for="pollDuration">
            Poll Duration
        </label>

        <?php if($poll_fields_locked){ ?>

        <input
            type="hidden"
            name="poll_duration"
            value="<?=htmlspecialchars(
                (string)$poll_duration,
                ENT_QUOTES,
                'UTF-8'
            )?>"
        >

        <?php } ?>

        <select
            name="poll_duration"
            id="pollDuration"
            <?=$poll_fields_locked
                ? 'disabled'
                : ''
            ?>
        >
            <option
                value="1"
                <?=$poll_duration === 1
                    ? 'selected'
                    : ''
                ?>
            >
                1 Day
            </option>

            <option
                value="3"
                <?=$poll_duration === 3
                    ? 'selected'
                    : ''
                ?>
            >
                3 Days
            </option>

            <option
                value="7"
                <?=$poll_duration === 7
                    ? 'selected'
                    : ''
                ?>
            >
                7 Days
            </option>

            <option
                value="0"
                <?=$poll_duration === 0
                    ? 'selected'
                    : ''
                ?>
            >
                No End Date
            </option>
        </select>

    </div>

</div>

<?php } ?>

<?php } ?>
    

      <div class="pc-field" id="postTitleField">
        <label id="postTitleLabel" for="postTitleInput">
            Post Title
        </label>

        <input
            type="text"
            name="blog_name"
            id="postTitleInput"
            placeholder="Write your post title"
            value="<?=htmlspecialchars($blog_name)?>"
            required
            <?=(
                $post_type === 'poll'
                &&
                $poll_fields_locked
            )
                ? 'readonly'
                : ''
            ?>
        >
      </div>

      <div class="pc-field" id="postTagsField">
        <label for="postTagsInput">
            Tags
        </label>

        <input
            type="text"
            name="heading"
            id="postTagsInput"
            placeholder="Write some tags for your post"
            value="<?=htmlspecialchars($heading)?>"
        >
      </div>

      <div class="pc-field" id="postDescriptionField">
        <label
            id="postDescriptionLabel"
            for="postDescriptionInput"
        >
            Post Description
        </label>

        <textarea
            name="short_des"
            id="postDescriptionInput"
            rows="4"
            placeholder="Write something about your post"
        ><?=htmlspecialchars($short_des)?></textarea>
      </div>

      <details class="advanced-box" id="postMetaFields">
        <summary>Add Meta Tags</summary>

        <div class="pc-field mt12">
          <label>Meta Title</label>
          <input type="text" name="metetitle" placeholder="Write meta title" maxlength="100" value="<?=htmlspecialchars($metetitle)?>">
        </div>

        <div class="pc-field mt12">
          <label>Meta Description</label>
          <input type="text" name="metades" placeholder="Write meta description" maxlength="200" value="<?=htmlspecialchars($metades)?>">
        </div>

        <div class="pc-field mt12">
          <label>Meta Keywords</label>
          <input type="text" name="othur_name" placeholder="Write meta keywords" maxlength="200" value="<?=htmlspecialchars($othur_name)?>">
        </div>
      </details>

      <div class="pc-submit">

        <?php if(!empty($id)){ ?>

        <a
            href="/wall/user/user-view-wall.php"
            class="cancel-post-btn"
        >
            Cancel
        </a>

        <?php } ?>

        <button
            type="submit"
            class="publish-btn"
        >
            <?=!empty($id) ? 'Update Post' : 'Publish Post'?>
        </button>

      </div>

    </form>
    
<?php if(empty($id)){ ?>
<div class="crop-modal" id="cropModal">
  <div class="crop-modal-content">
    <span class="close-crop" id="closeCrop">&times;</span>

    <div class="crop-title">Crop Your Image</div>

	<div class="crop-ratio-switch">
  	<button type="button" class="ratio-btn active" id="squareBtn">Square</button>
  	<button type="button" class="ratio-btn" id="portraitBtn">Portrait</button>
  	<button type="button" class="ratio-btn" id="landscapeBtn">Landscape</button>
	</div>
    
	<div class="crop-actions">
  	<button type="button" id="rotateLeft">⟲ Rotate Left</button>
  	<button type="button" id="rotateRight">⟳ Rotate Right</button>
	</div>    
    <div class="crop-container">
      <img id="cropImage">
    </div>

    <button type="button" class="crop-btn" id="cropBtn">Crop & Use Image</button>
  </div>
</div>

<?php } ?>

<?php if(
    empty($id)
    ||
    (
        $post_type === 'poll'
        &&
        !$poll_fields_locked
    )
){ ?>

<div
    class="crop-modal poll-option-crop-modal"
    id="pollOptionCropModal"
    role="dialog"
    aria-modal="true"
    aria-labelledby="pollOptionCropTitle"
>
    <div class="crop-modal-content">

        <button
            type="button"
            class="close-crop"
            id="closePollOptionCrop"
            aria-label="Close poll option image cropper"
        >
            &times;
        </button>

        <div
            class="crop-title"
            id="pollOptionCropTitle"
        >
            Crop Poll Option Image
        </div>

        <p class="poll-option-crop-help">
            The image will be cropped to a square.
        </p>

        <div class="crop-actions">

            <button
                type="button"
                id="pollOptionRotateLeft"
            >
                ⟲ Rotate Left
            </button>

            <button
                type="button"
                id="pollOptionRotateRight"
            >
                ⟳ Rotate Right
            </button>

        </div>

        <div class="crop-container">

            <img
                id="pollOptionCropImage"
                src=""
                alt=""
            >

        </div>

        <button
            type="button"
            class="crop-btn"
            id="usePollOptionCrop"
        >
            Crop & Use Image
        </button>

    </div>
</div>

<?php } ?>
  </div>
</div>


  </div>
</div>
<?php } ?>





<!-- RIGHT SIDEBAR -->
<div class="sidebar">
<!-- LATEST POSTS -->
<?php include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/latest-post-slider.php"); ?>
<!-- HAI BLOG SLIDER -->
<?php include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/hai-blog-slider.php"); ?>
<!-- FOLLOW US -->
<?php include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/follow-us.php"); ?>
</div>
</div>

<!-- FOOTER -->
<?php include($_SERVER['DOCUMENT_ROOT']."/wall/bcknds/footer.php"); ?>


<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>

<script src="../bcknds/hai-blog-slidr.js"></script>
<script src="../bcknds/search.js"></script>
<script src="../bcknds/user-menu.js"></script>
<script src="../bcknds/create-post.js?v=20260801-1"></script>

<a href="javascript:history.back()" class="back-floating"><i class="fa fa-arrow-left"></i></a></body>
</html>