<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
    session_start();
    include "databaseConnect.php";

    $type = '';
    if(isset($_REQUEST['type']) && !empty($_REQUEST['type'])){
        $type = $_REQUEST['type'];
    }

    if ($type === "addForm") {
        // echo "<pre>";
        // print_r($_POST);die;
        $hotelName = mysqli_real_escape_string($conn, $_POST['addhotelName']);
        $pageHeading = mysqli_real_escape_string($conn, $_POST['addPageHeading']);
        $hotelLink = mysqli_real_escape_string($conn, $_POST['addhotelLink']);
        $ratingComment = mysqli_real_escape_string($conn, $_POST['addRatingComment']);
        $reviewNumber = mysqli_real_escape_string($conn, $_POST['addReviewNumber']);
        $pricing = mysqli_real_escape_string($conn, $_POST['addPricing']);
        $freeCancellation = $_POST['addFreeCancellation'] == 'on' ? 1 : $_POST['addFreeCancellation'];
        $noPrePayment = $_POST['addNoPre-payment'] == 'on' ? 1 : $_POST['addNoPre-payment'];
        $hotelAddress = mysqli_real_escape_string($conn, $_POST['addHotelAddress']);
        $googleMapURL = mysqli_real_escape_string($conn, $_POST['googleMapURL']);
        $slugUrl = mysqli_real_escape_string($conn, $_POST['addslugUrl']);
        $amenities = mysqli_real_escape_string($conn, $_POST['hotelAmenities']);
        $addImageURL = mysqli_real_escape_string($conn, $_POST['addImageURL']);


        $uploadDir = '/var/www/html/myairtrip/offers/images/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
    
        $imageURL = '';
        if (isset($_FILES['addPageImageURL']) && $_FILES['addPageImageURL']['error'] === 0) {
            $imageTmpName = $_FILES['addPageImageURL']['tmp_name'];
            $imageName = uniqid() . '-' . basename($_FILES['addPageImageURL']['name']);
            $imagePath = $uploadDir . $imageName;
    
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (in_array($_FILES['addPageImageURL']['type'], $allowedTypes)) {
                if (move_uploaded_file($imageTmpName, $imagePath)) {
                    $imageURL = $imageName;
                } else {
                    echo json_encode(["success" => false, "message" => "Failed to upload image."]);
                    exit;
                }
            } else {
                echo json_encode(["success" => false, "message" => "Invalid image type. Only JPG, PNG, and GIF are allowed."]);
                exit;
            }
        }
    
        $sql = "INSERT INTO tblhoteldetails (hotel_name, hotel_link, rating_comment, review_number, pricing, free_cancellation, no_pre_payment, hotel_address, image_url, hotel_location , slug, amenities, page_heading, page_backgroung_Image)
                VALUES ('$hotelName', '$hotelLink', '$ratingComment', '$reviewNumber', '$pricing', '$freeCancellation', '$noPrePayment', '$hotelAddress', '$addImageURL', '$googleMapURL', '$slugUrl', '$amenities', '$pageHeading', '$imageURL')";
    
        if (mysqli_query($conn, $sql)) {
            echo json_encode(["success" => true, "message" => "Hotel added successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => "Error: " . mysqli_error($conn)]);
        }
    }else if($type === 'editForm') {
        // echo "<pre>";
        // print_r($_POST);die;
        $hotel_id = mysqli_real_escape_string($conn, $_POST['hotelID']);
        $hotelName = mysqli_real_escape_string($conn, $_POST['edithotelName']);
        $pageHeading = mysqli_real_escape_string($conn, $_POST['editPageHeading']);
        $hotelLink = mysqli_real_escape_string($conn, $_POST['edithotelLink']);
        $ratingComment = mysqli_real_escape_string($conn, $_POST['editRatingComment']);
        $reviewNumber = mysqli_real_escape_string($conn, $_POST['editReviewNumber']);
        $pricing = mysqli_real_escape_string($conn, $_POST['editPricing']);
        $freeCancellation = $_POST['editFreeCancellation'] == 'on' ? 1 : $_POST['editFreeCancellation'];
        $noPrePayment = $_POST['editNoPre-payment'] == 'on' ? 1 : $_POST['editNoPre-payment'];
        $hotelAddress = mysqli_real_escape_string($conn, $_POST['editHoteleditress']);
        $googleMapURL = mysqli_real_escape_string($conn, $_POST['editgoogleMapURL']);
        $slugUrl = mysqli_real_escape_string($conn, $_POST['editslug']);
        $amenities = mysqli_real_escape_string($conn, $_POST['hotelAmenities']);
        $editImageURL = mysqli_real_escape_string($conn, $_POST['editImageURL']);

    
        if (isset($_FILES['editImageFile']) && $_FILES['editImageFile']['error'] == UPLOAD_ERR_OK) {
            $imageURL = mysqli_real_escape_string($conn, $_POST['editImageURL']);
            $targetDir = "images/";
            $targetFile = $targetDir . basename($_FILES['editImageFile']['name']);
            $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    
            $validExtensions = ["jpg", "jpeg", "png", "gif"];
            if (!in_array($imageFileType, $validExtensions)) {
                die("Invalid file type. Only JPG, JPEG, PNG & GIF are allowed.");
            }
            if ($_FILES['editImageFile']['size'] > 2000000) { 
                die("File size exceeds limit. Max 2MB allowed.");
            }
    
            if (move_uploaded_file($_FILES['editImageFile']['tmp_name'], $targetFile)) {
                $imageURL = basename($_FILES['editImageFile']['name']); 
            } else {
                die("Failed to upload image.");
            }
        }else{
            $imageURL = mysqli_real_escape_string($conn, $_POST['editImageURL_older']);
        }
    
        $sql = "UPDATE tblhoteldetails SET 
                    hotel_name = '$hotelName', 
                    hotel_link = '$hotelLink', 
                    rating_comment = '$ratingComment',
                    review_number = '$reviewNumber',
                    pricing = '$pricing',
                    free_cancellation = '$freeCancellation',
                    no_pre_payment = '$noPrePayment',
                    hotel_address = '$hotelAddress',
                    image_url = '$editImageURL',
                    hotel_location = '$googleMapURL',
                    slug = '$slugUrl',
                    amenities = '$amenities',
                    page_heading = '$pageHeading',
                    page_backgroung_Image = '$imageURL'
                WHERE hotel_id = '$hotel_id'";
    
        if (mysqli_query($conn, $sql)) {
            header('location:admin.php?msg=success');
        } else {
            echo json_encode(["success" => false, "message" => "Error: " . mysqli_error($conn)]);
        }
    }else if($type === 'addFormsidebar-1'){
        $slug = mysqli_real_escape_string($conn, $_POST['addBySlug']);
        $hotelAttractionsContent = mysqli_real_escape_string($conn, $_POST['hotelAttractionsContent']);
        $links = mysqli_real_escape_string($conn, $_POST['addhotelAttractionsLinks']);

        $sql = "INSERT INTO tbltopattractions (slug, hotelAttractionsContent, hotelAttractionsLinks) VALUES ('$slug', '$hotelAttractionsContent', '$links')";
        if (mysqli_query($conn, $sql)) {
            echo "Data inserted successfully!";
            header("Location: top-attractions.php?message=success");
            exit;
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    }else if($type === 'editFormsidebar-1'){
        $id = intval($_POST['id']);
        $slug = mysqli_real_escape_string($conn, $_POST['addBySlug']);
        $hotelAttractionsContent = mysqli_real_escape_string($conn, $_POST['hotelAttractionsContent']);
        $hotelAttractionsLinks = mysqli_real_escape_string($conn, $_POST['hotelAttractionsLinks']);

        if (empty($id)) {
            echo "Invalid ID.";
            exit;
        }
        if (empty($slug)) {
            echo "Slug is required.";
            exit;
        }
        if (empty($hotelAttractionsContent)) {
            echo "Attractions Content is required.";
            exit;
        }
        if (empty($hotelAttractionsLinks)) {
            echo "Attraction Links are required.";
            exit;
        }

        $sql = "UPDATE tbltopattractions 
                SET slug = '$slug', hotelAttractionsContent = '$hotelAttractionsContent', hotelAttractionsLinks = '$hotelAttractionsLinks'
                WHERE id = $id";

        if (mysqli_query($conn, $sql)) {
            echo "Data updated successfully!";
            header("Location:top-attractions.php?message=success");
            exit;
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    }else if($type === 'addFormsidebar-2'){
        $slug = isset($_POST['addBySlug']) ? trim($_POST['addBySlug']) : '';
        $timeToVisitContent = isset($_POST['hoteltimeToVisitContent']) ? trim($_POST['hoteltimeToVisitContent']) : '';
        
        if (empty($slug)) {
            echo json_encode(['status' => 'error', 'message' => 'Slug is required.']);
            exit;
        }
    
        if (empty($timeToVisitContent)) {
            echo json_encode(['status' => 'error', 'message' => 'Content for Best Time to Visit is required.']);
            exit;
        }

        $sql = "INSERT INTO tbltimetovisit (slug, timetovisitcontent) VALUES ('$slug', '$timeToVisitContent')";
        if (mysqli_query($conn, $sql)) {
            echo "Data inserted successfully!";
            header("Location: time-to-visit.php?message=success");
            exit;
        } else {
            echo "Error: " . mysqli_error($conn);
        }

    }else if($type === 'editFormsidebar-2'){
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $slug = isset($_POST['addBySlug']) ? trim($_POST['addBySlug']) : '';
        $timeToVisitContent = isset($_POST['hoteledittimetovisit']) ? trim($_POST['hoteledittimetovisit']) : '';

        if (empty($id)) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid ID.']);
            exit;
        }

        if (empty($slug)) {
            echo json_encode(['status' => 'error', 'message' => 'Slug is required.']);
            exit;
        }

        if (empty($timeToVisitContent)) {
            echo json_encode(['status' => 'error', 'message' => 'Content for Best Time to Visit is required.']);
            exit;
        }

        $sql = "UPDATE tbltimetovisit 
                SET slug = '$slug', timetovisitcontent = '$timeToVisitContent' 
                WHERE id = $id";

        if (mysqli_query($conn, $sql)) {
            echo "Data updated successfully!";
            header("Location: time-to-visit.php?message=success");
            exit;
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    }else if($type === 'addPageContent'){
        $slug = mysqli_real_escape_string($conn, $_POST['addBySlug']);
        $contentCategory = intval($_POST['addByCategory']); 
        $pageContent = mysqli_real_escape_string($conn, $_POST['addPageContent']);

        if (empty($slug)) {
            die(json_encode(['status' => 'error', 'message' => 'Page slug is required']));
        }
        if (empty($contentCategory)) {
            die(json_encode(['status' => 'error', 'message' => 'Content category is required']));
        }
        if (empty($pageContent)) {
            die(json_encode(['status' => 'error', 'message' => 'Page content is required']));
        }

        $sql = "INSERT INTO tblpagecontent (slug, pagecontent, contentcategory) 
                VALUES ('$slug', '$pageContent', '$contentCategory')
                ON DUPLICATE KEY UPDATE 
                    pagecontent = '$pageContent',
                    contentcategory = '$contentCategory'";

        if (mysqli_query($conn, $sql)) {
            echo json_encode(['status' => 'success', 'message' => 'Page content added/updated successfully']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Error: ' . mysqli_error($conn)]);
        }
    }else if($type === 'addFaqs'){
        $slug = mysqli_real_escape_string($conn, $_POST['addBySlug']);
        if (empty($slug)) {
            echo "Please select a valid slug.";
            exit;
        }
        $questions = $_POST['question'];
        $answers = $_POST['answer'];

        // echo count($questions);die;

        if (is_array($questions) && is_array($answers) && count($questions) === count($answers)) {
            $insertedRows = 0;
            for ($i = 0; $i < count($questions); $i++) {
                $question = mysqli_real_escape_string($conn, trim($questions[$i]));
                $answer = mysqli_real_escape_string($conn, trim($answers[$i]));

                if (!empty($question) && !empty($answer)) {
                    echo $sql = "INSERT INTO tblpagefaqs (slug, question, answer) VALUES ('$slug', '$question', '$answer')";
                    if (mysqli_query($conn, $sql)) {
                        $insertedRows++;
                    } else {
                        echo "Error: " . mysqli_error($conn);
                    }
                }
            }

            if ($insertedRows > 0) {
                header('location:add-faqs.php?msg=200');
            } else {
                echo "No FAQs were added. Please fill out the form correctly.";
            }
        } else {
            echo "Invalid input. Please fill out all fields.";
        }
    }else if ($type === 'getFaqs') {
        $slug = mysqli_real_escape_string($conn, $_GET['slug']);
        $sql = "SELECT id, question, answer FROM tblpagefaqs WHERE slug = '$slug'";
        $result = mysqli_query($conn, $sql);
        $faqs = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $faqs[] = $row;
            // print_r($row);
        }
        echo json_encode($faqs);
        exit;
    }else if ($type === 'editFaqs') {
        // echo "<pre>";
        // print_r($_POST);die;
        $slug = mysqli_real_escape_string($conn, $_POST['addBySlug']);
        
        if (empty($slug)) {
            echo "Please select a valid slug.";
            exit;
        } 
        $questions = '';
        if(isset($_POST['question']) && !empty($_POST['question'])){
            $questions = $_POST['question'];
        } 
        $answers = '';  
        if(isset($_POST['answer']) && !empty($_POST['answer'])){
            $answers = $_POST['answer'];
        }
        
        if (is_array($questions) && is_array($answers) && count($questions) === count($answers)) {
            $updatedRows = 0;
            $deleteSql = "DELETE FROM tblpagefaqs WHERE slug = '$slug'";
            if (!mysqli_query($conn, $deleteSql)) {
                echo "Error deleting old FAQs: " . mysqli_error($conn);
                exit;
            }
            for ($i = 0; $i < count($questions); $i++) {
                $question = mysqli_real_escape_string($conn, trim($questions[$i]));
                $answer = mysqli_real_escape_string($conn, trim($answers[$i]));
    
                if (!empty($question) && !empty($answer)) {
                    $insertSql = "INSERT INTO tblpagefaqs (slug, question, answer) VALUES ('$slug', '$question', '$answer')";
                    if (mysqli_query($conn, $insertSql)) {
                        $updatedRows++;
                    } else {
                        echo "Error: " . mysqli_error($conn);
                    }
                }
            }    
            if ($updatedRows > 0) {
                header('location:edit-faqs.php?msg=200');
                exit;
            } else {
                echo "No FAQs were updated. Please fill out the form correctly.";
            }
        } else {
            echo "Invalid input. Please fill out all fields.";
        }
    }if ($type === 'addMeta') {
        // echo "<pre>";
        // print_r($_POST);die;
        $pageSlug = isset($_POST['pageSlug']) ? trim($_POST['pageSlug']) : '';
        $metaTitle = isset($_POST['metaTitle']) ? trim($_POST['metaTitle']) : '';
        $metaDescription = isset($_POST['metaDescription']) ? trim($_POST['metaDescription']) : '';
        $metaKeywords = isset($_POST['metakeywords']) ? trim($_POST['metakeywords']) : '';
        $noindexTag = isset($_POST['addFreeCancellation']) && $_POST['addFreeCancellation'] === 'on' ? 1 : 0;
    
        if (empty($pageSlug)) {
            echo json_encode(['status' => 'error', 'message' => 'Page Slug required.']);
            exit;
        }    
        $sql = "INSERT INTO tblmetatags (slug, metaTitle, metaDescription, metaKeyword, noindexTag, createdDateTime, updatedDateTime) 
                VALUES ('$pageSlug', '$metaTitle', '$metaDescription', '$metaKeywords', $noindexTag, NOW(), NOW())";
        if (mysqli_query($conn, $sql)) {
            header('location:meta.php?msg=200');
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to add meta tag: ' . mysqli_error($conn)]);
        }
    } elseif ($type === 'editMeta') {
        $metaId = isset($_POST['metaId']) ? intval($_POST['metaId']) : 0;
        $pageSlug = isset($_POST['pageSlug']) ? trim($_POST['pageSlug']) : '';
        $metaTitle = isset($_POST['metaTitle']) ? trim($_POST['metaTitle']) : '';
        $metaDescription = isset($_POST['metaDescription']) ? trim($_POST['metaDescription']) : '';
        $metaKeywords = isset($_POST['metakeywords']) ? trim($_POST['metakeywords']) : '';
        $noindexTag = isset($_POST['addFreeCancellation']) && $_POST['addFreeCancellation'] === 'on' ? 1 : 0;
    
        if ($metaId <= 0 || empty($pageSlug)) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid data. Meta ID, Page Slug are required.']);
            exit;
        }
    
        $sql = "UPDATE tblmetatags 
                SET slug = '$pageSlug', metaTitle = '$metaTitle', metaDescription = '$metaDescription', 
                    metaKeyword = '$metaKeywords', noindexTag = $noindexTag, updatedDateTime = NOW() 
                WHERE metaId = $metaId";
        if (mysqli_query($conn, $sql)) {
            header('location:meta.php?msg=200');
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to update meta tag: ' . mysqli_error($conn)]);
        }
    
        mysqli_close($conn);
    }
    
    
    mysqli_close($conn);
?>
