<?php
    include("config.php");
    include("functions.php");
    header('Access-Control-Allow-Origin: *');

    session_start();
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);

    
    if(isset($_POST['signin-request']))  /* This will be the hidden field for all conditions*/
    {
        $user_email = $_POST['email'];
        $user_password = $_POST['password'];

        $queryMatch = "SELECT * from users where email = '".$user_email."' AND password = '".md5($user_password)."' AND deleted <> 1 ";
        $dataMatch = mysqli_query($conn, $queryMatch);

        if($dataMatch->num_rows > 0)
        {
            
            while($row=mysqli_fetch_assoc($dataMatch))
            {
                $_SESSION["loggedin_id"] = $row['id'];
                $_SESSION["loggedin_name"] = $row['fname'];
                $_SESSION["loggedin_email"] = $row['email'];

                echo json_encode(array('success'=>1, 'msg' => "Welcome, Admin"));
            }
            
        }
        else
        {
            echo json_encode(array('success'=>0, 'msg' => "Email or Password is incorrect .."));  
        }

    }


    if(isset($_POST['update-user-request'])){  /* This will be the hidden field for all conditions*/

        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $uname = $_POST['uname'];
        $email = $_POST['email'];

        // VALIDATIONS ___________________
        if($fname==""){
            echo json_encode(array('success' => 0, 'msg' => "First Name can not be empty")); die();
        }
        if($lname==""){
            echo json_encode(array('success' => 0, 'msg' => "Last Name can not be empty")); die();
        }
        if($uname==""){
            echo json_encode(array('success' => 0, 'msg' => "User Name can not be empty")); die();
        }
        if($email==""){
            echo json_encode(array('success' => 0, 'msg' => "Email can not be empty")); die();
        }
     
        // VALIDATIONS ___________________

        $usr_id = $_POST['usr_id'];
        

        $query_update = "UPDATE users
        SET uname = '".$uname."', fname = '".$fname."' , lname = '".$lname."', email ='".$email."' WHERE id = '".$usr_id."'";
            
        $run = mysqli_query($conn, $query_update);

        if(isset($run)){
            echo json_encode(array('success'=>1, 'msg' => "Update Successfully ..!"));
        }else{
            echo json_encode(array('success'=>0, 'msg' => "Something went wrong, please try again later ..!"));
        }
    }
    
    if(isset($_GET['delete-user-request'])){  /* This will be the hidden field for all conditions*/

        // $password = $_POST['password'];
        $usr_id = $_GET['delete-user-request'];

        $query = " DELETE FROM users WHERE id = '".$usr_id."' ";
        $run = mysqli_query($conn, $query);

        if($run){
            header("location: https://gaspmakercargo.com/app/admin/all-users.php");
            // echo json_encode(array('error'=>0, 'msg' => "Deleted Successfully ..!"));
        }else{
            header("location: https://gaspmakercargo.com/app/admin/all-users.php");
        }
    }


    
    if(isset($_POST['update-user-password-request'])){  /* This will be the hidden field for all conditions*/

        $password = $_POST['password'];
        $c_password = $_POST['c_password'];
        $usr_id = $_POST['usr_id'];


        // VALIDATIONS ___________________
        if($c_password != $password){
            echo json_encode(array('success' => 0, 'msg' => "Paswword Doesn't match")); die();
        }
        if(strlen($password) < 8){
            echo json_encode(array('success' => 0, 'msg' => "Paswword must be 8 characters")); die();
        }
     
        // VALIDATIONS ___________________

        $query_update = "UPDATE users
        SET password = '".md5($password)."'
        WHERE id = '".$usr_id."'
        ";

        $run = mysqli_query($conn, $query_update);

        if($run){
            echo json_encode(array('success'=>1, 'msg' => "Update Successfully ..!"));
        }else{
            echo json_encode(array('success'=>0, 'msg' => "Something went wrong, please try again later ..!"));
        }
        
    }
    
    
    //Contact us page request data
    if(isset($_POST['enquiry-add-request']))  /* This will be the hidden field for all conditions*/
    {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $message = $_POST['message'];

        // VALIDATIONS ___________________
        if($name==""){
            echo json_encode(array('success' => 0, 'msg' => "Name can not be empty")); die();
        }
        if($email==""){
            echo json_encode(array('success' => 0, 'msg' => "Email can not be empty")); die();
        }
        if($message==""){
            echo json_encode(array('success' => 0, 'msg' => "Please Add Message")); die();
        }

        // VALIDATIONS ___________________

        $query = "INSERT INTO enquiriesFromCustomers (name, email, phone, message)
            VALUES ('".$name."', '".$email."', '".$phone."', '".$message."')";
       
        $run = mysqli_query($conn, $query);

        if($run){
            echo json_encode(array('success'=>1, 'msg' => "Message Sent ..!"));
        }else{
            echo json_encode(array('success'=>0, 'msg' => "Something went wrong, please try again later ..!"));
        }

    }
    
    if(isset($_GET['enquiry-delete-request'])){ 

        $id = $_GET['enquiryId'];

        $query_update = "DELETE FROM enquiriesFromCustomers WHERE id = '".$id."'";

        $run = mysqli_query($conn, $query_update);

        if($run){
            header("location: king/all-enquiries.php?deleted=1");
        }
            else{
            header("location: king/all-enquiries.php?deleted=0");
        }
    }
    
    
if (isset($_POST['feedbackform-request'])) {

    // TEMP: show PHP errors in response so we can see 500 cause
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    header('Content-Type: application/json');

    $name      = isset($_POST['name']) ? trim($_POST['name']) : '';
    $number    = isset($_POST['number']) ? trim($_POST['number']) : '';
    $rating1   = isset($_POST['FoodQualityrating']) ? (int) $_POST['FoodQualityrating'] : 0;
    $rating2   = isset($_POST['FoodPresentationrating']) ? (int) $_POST['FoodPresentationrating'] : 0;
    $rating3   = isset($_POST['Atmosphererating']) ? (int) $_POST['Atmosphererating'] : 0;
    $rating4   = isset($_POST['Ambiancerating']) ? (int) $_POST['Ambiancerating'] : 0;
    $rating5   = isset($_POST['Servicerating']) ? (int) $_POST['Servicerating'] : 0;
    $message   = isset($_POST['message']) ? trim($_POST['message']) : '';
    $branch_id = isset($_POST['branch_id']) ? (int) $_POST['branch_id'] : 0;

    // Legacy columns required by strict SQL mode but not used by the public form
    $email = ''; // optional/unknown on public form
    $dob   = '0';
    $feed_1 = '';
    $feed_2 = '';
    $feed_3 = '';
    $feed_4 = '';
    $feed_5 = '';
    $deleted = 0;

    // VALIDATIONS ___________________
    if ($name === '') {
        echo json_encode(array('success' => 0, 'msg' => 'Name cannot be empty')); die();
    }
    if ($number === '') {
        echo json_encode(array('success' => 0, 'msg' => 'Mobile No cannot be empty')); die();
    }
    // branch_id is required to link feedback to a branch
    if ($branch_id <= 0) {
        echo json_encode(array('success' => 0, 'msg' => 'Branch information is missing or invalid.')); die();
    }
    // message is optional now, so no validation here

    // Escape for safety
    $name    = mysqli_real_escape_string($conn, $name);
    $number  = mysqli_real_escape_string($conn, $number);
    $message = mysqli_real_escape_string($conn, $message);

    // INSERT NEW FEEDBACK (fill all NOT NULL legacy columns to satisfy strict SQL mode)
    $insertQuery = "INSERT INTO feedbacks 
        (name, email, number, dob, FoodQualityrating, FoodPresentationrating, Atmosphererating, Ambiancerating, Servicerating, message, branch_id, feed_1, feed_2, feed_3, feed_4, feed_5, deleted) 
        VALUES (
            '".$name."',
            '".$email."',
            '".$number."',
            '".$dob."',
            '".$rating1."',
            '".$rating2."',
            '".$rating3."',
            '".$rating4."',
            '".$rating5."',
            '".$message."',
            '".$branch_id."',
            '".$feed_1."',
            '".$feed_2."',
            '".$feed_3."',
            '".$feed_4."',
            '".$feed_5."',
            '".$deleted."'
        )";

    $runInsert = mysqli_query($conn, $insertQuery);

    if ($runInsert) {
        echo json_encode(array('success' => 1, 'msg' => 'Successfully Added!')); die();
    } else {
        echo json_encode(array(
            'success' => 0,
            'msg'     => 'Database error while saving feedback: '.mysqli_error($conn)
        )); die();
    }
}
    
    
    // ADMIN BRANCH Functions _________________________
    if(isset($_POST['add-branch-request']))  /* This will be the hidden field for all conditions*/
    {
        // DEBUG: ensure we see any PHP errors for this endpoint (especially on VPS)
        ini_set('display_errors', '1');
        ini_set('display_startup_errors', '1');
        error_reporting(E_ALL);
        header('Content-Type: application/json');

        $name = $_POST['name'];
        
        $title = $_POST['title'];
        $about = $_POST['about'];

        $feed_1 = $_POST['feed_1'];
        $feed_2 = $_POST['feed_2'];
        $feed_3 = $_POST['feed_3'];
        $feed_4 = $_POST['feed_4'];
        $feed_5 = $_POST['feed_5'];

        // VALIDATIONS ___________________
        if($name==""){
            echo json_encode(array('success' => 0, 'msg' => "Name can not be empty")); die();
        }

        // VALIDATIONS ___________________

        // Explicitly set all NOT NULL fields to satisfy strict SQL mode on VPS
        // Initial logo is empty; it will be updated below if files are uploaded.
        $defaultLocation = "uploads/";
        $query = "INSERT INTO branches (name, active, deleted, feed_1, feed_2, feed_3, feed_4, feed_5, title, about, location, logo)
            VALUES (
                '".$name."',
                1,
                0,
                '".$feed_1."',
                '".$feed_2."',
                '".$feed_3."',
                '".$feed_4."',
                '".$feed_5."',
                '".$title."',
                '".$about."',
                '".$defaultLocation."',
                ''
            )";
       
        $run = mysqli_query($conn, $query);
        
        $updated_ID = $conn->insert_id;

         // $updated_ID = $_POST['company_id'];

        $valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg");
        $path = "uploads/";
        $image_name_all = array();

        // Logo is optional; only process when at least one file is actually selected
        if (!empty($_FILES['company_logo']['name'][0])) {
            $total_images= count($_FILES['company_logo']['name']);

            for($i=0; $i <= $total_images-1; $i++){

                $fileName2   = $_FILES['company_logo']['name'][$i];
                $fileSize2   = $_FILES['company_logo']['size'][$i];
                $filetmpName = $_FILES['company_logo']['tmp_name'][$i];
                $mimeType    = isset($_FILES['company_logo']['type'][$i]) ? $_FILES['company_logo']['type'][$i] : '';

                if (empty($fileName2) || empty($mimeType)) {
                    // nothing selected in this slot; skip
                    continue;
                }

                $ext2 = explode("/",$mimeType);
                $extension = isset($ext2[1]) ? strtolower($ext2[1]) : '';

                if(in_array($extension,$valid_file_formats)) {
                    if($fileSize2<(1502444*1502444)) {
                        $image_name = time().$i.".".$extension;
                        if(move_uploaded_file($filetmpName, $path.$image_name)){
                            $image_name_all[] = $image_name;
                        }
                        // If move_uploaded_file fails, treat logo as optional and simply skip it.
                    } else {
                        // File too large; skip this image but don't block branch creation.
                        continue;
                    }
                } else {
                    // Invalid format; skip this image but don't block branch creation.
                    continue;
                }
            }

            if (!empty($image_name_all)) {
                $image_name_all = implode(",",$image_name_all);
                $sql2 = "UPDATE branches SET logo='".$image_name_all."',location='".$path."' WHERE id='".$updated_ID."' ";
                $result2 = mysqli_query($conn, $sql2) or die("error to update image data");
            }
        }



        if($run){
            echo json_encode(array('success'=>1, 'msg' => "Branch added successfully.")); die();
        }else{
            echo json_encode(array('success'=>0, 'msg' => "Database error while adding branch: ".mysqli_error($conn))); die();
        }

    }
    if(isset($_GET['branch-delete-request'])){  /* This will be the hidden field for all conditions*/

        $id = $_GET['branch_id'];

        $query_update = "UPDATE branches
            SET deleted = '1'
            WHERE id = '".$id."'
            ";

        $run = mysqli_query($conn, $query_update);

        if($run){
            header("location: all-branches.php");
        }
            else{
            header("location: all-branches.php");
        }
    }

    if(isset($_POST['admin-update-branch-request']))  /* This will be the hidden field for all conditions*/
    {
        $id = $_POST['branch_id'];
        $name = $_POST['name'];
        $approved = 1;

        $title = $_POST['title'];
        $about = $_POST['about'];

        $feed_1 = $_POST['feed_1'];
        $feed_2 = $_POST['feed_2'];
        $feed_3 = $_POST['feed_3'];
        $feed_4 = $_POST['feed_4'];
        $feed_5 = $_POST['feed_5'];


        // VALIDATIONS ___________________
        if($name==""){
            echo json_encode(array('success' => 0, 'msg' => "Branch can not be empty")); die();
        }
        // VALIDATIONS ___________________

        
        // DUPLICATE CHECK _________________
        $queryMatch = "SELECT * from branches where name = '".$name."' AND id <> '".$id."' ";
        $dataMatch = mysqli_query($conn, $queryMatch);
        if($dataMatch->num_rows > 0)
        {
            $errorMsg = "Branch ".$name." already registered..";
            $data = array('success' => 0, 'msg' => $errorMsg);
            echo json_encode($data);
        }else{

            $query_update = "UPDATE branches
                SET name = '".$name."',
                active = '".$approved."',
                title = '".$title."',
                about = '".$about."',
                feed_1 = '".$feed_1."',
                feed_2 = '".$feed_2."',
                feed_3 = '".$feed_3."',
                feed_4 = '".$feed_4."',
                feed_5 = '".$feed_5."',
                deleted = '0'
                WHERE id = '".$id."'
                ";
            $run = mysqli_query($conn, $query_update);

               $updated_ID = $id;

         // $updated_ID = $_POST['company_id'];

        $valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg");
        $path = "uploads/";
        $total_images= count($_FILES['company_logo']['name']);
        $image_name_all = array();

        for($i=0; $i <= $total_images-1; $i++){

            $fileName2 = $_FILES['company_logo']['name'][$i];
            $fileSize2 = $_FILES['company_logo']['size'][$i];
            $filetmpName = $_FILES['company_logo']['tmp_name'][$i];
            $ext2 = explode("/",$_FILES['company_logo']['type'][$i]);

            if(count($ext2) > 1){

                if(in_array($ext2[1],$valid_file_formats)) {
                    if($fileSize2<(1502444*1502444)) {
                        $image_name = time().$i.".".$ext2[1];
                        if(move_uploaded_file($filetmpName, $path.$image_name)){
                            $image_name_all[] = $image_name;
                        }
                    else
                        {echo json_encode(array('error'=>1, 'msg' => " Image Upload failed..!"));die();}
                    }
                    else
                        {echo json_encode(array('error'=>1, 'msg' => " Image file size maximum 1 MB..!"));die();}
                }
                else
                    {echo json_encode(array('error'=>1, 'msg' => " Invalid file format..!"));die();}

            }
        }
        if(!empty($image_name_all)){
            $image_name_all = implode(",",$image_name_all);
            $sql2 = "UPDATE branches SET logo='".$image_name_all."',location='".$path."' WHERE id='".$updated_ID."' ";
            $result2 = mysqli_query($conn, $sql2) or die("error to update image data");
        }

            if(isset($run)){
                $data = array('success' => 1, 'msg' => "Successfully Updated !");
                echo json_encode($data);
            }else{
                $data = array('success' => 0, 'msg' => "Something went Wrong !");
                echo json_encode($data);
            }
        }

    }
    // ADMIN BRANCH Functions _________________________


    // ADMIN COMPANY Functions _________________________
    if(isset($_POST['admin-update-company-request']))  /* This will be the hidden field for all conditions*/
    {
        $updated_ID = $_POST['company_id'];

        $valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg");
        $path = "uploads/";
        $total_images= count($_FILES['company_logo']['name']);
        $image_name_all = array();

        for($i=0; $i <= $total_images-1; $i++){

            $fileName2 = $_FILES['company_logo']['name'][$i];
            $fileSize2 = $_FILES['company_logo']['size'][$i];
            $filetmpName = $_FILES['company_logo']['tmp_name'][$i];
            $ext2 = explode("/",$_FILES['company_logo']['type'][$i]);


            if(count($ext2) > 1){
                if(in_array($ext2[1],$valid_file_formats)) {
                    if($fileSize2<(1502444*1502444)) {
                        $image_name = time().$i.".".$ext2[1];
                        if(move_uploaded_file($filetmpName, $path.$image_name)){
                            $image_name_all[] = $image_name;
                        }
                    else
                        {echo json_encode(array('error'=>1, 'msg' => " Image Upload failed..!"));die();}
                    }
                    else
                        {echo json_encode(array('error'=>1, 'msg' => " Image file size maximum 1 MB..!"));die();}
                }
                else
                    {echo json_encode(array('error'=>1, 'msg' => " Invalid file format..!"));die();}
            }
        }
        $image_name_all = implode(",",$image_name_all);
        if(!empty($image_name_all)){

            $sql2 = "UPDATE company SET logo='".$image_name_all."',location='".$path."' WHERE id='".$updated_ID."' ";
            $result2 = mysqli_query($conn, $sql2) or die("error to update image data");
        }
        // echo json_encode($sql2);

        // if(isset($result2)){
            $data = array('success' => 1, 'msg' => "Successfully Updated !");
            echo json_encode($data);
        // }else{
            // $data = array('success' => 0, 'msg' => "Something went Wrong !");
            // echo json_encode($data);
        // }
    }
    // ADMIN COMPANY Functions _________________________


    // ADMIN USERS Functions _________________________
    if(isset($_POST['admin-add-user']))  /* This will be the hidden field for all conditions*/
    {
        
        $uname = $_POST['uname'];
        $role = $_POST['role'];

        $fname = $_POST['fname'];
        $lname = $_POST['lname'];

        $phone = $_POST['phone'];
        $city = $_POST['city'];

        $email = $_POST['email'];
        $password = $_POST['password'];


        // VALIDATIONS ___________________
        if($fname==""){
            echo json_encode(array('success' => 0, 'msg' => "First Name can not be empty")); die();
        }
        if($email==""){
            echo json_encode(array('success' => 0, 'msg' => "Email can not be empty")); die();
        }
        if($password==""){
            echo json_encode(array('success' => 0, 'msg' => "Please Enter Password")); die();
        }
        // VALIDATIONS ___________________

        $queryMatch = "SELECT * from users where email = '".$email."'  AND deleted <> 1";
        $dataMatch = mysqli_query($conn, $queryMatch);
        
        if($dataMatch->num_rows > 0)
        {
            $errorMsg = "Email Already registered, Please try a different one";
            $data = array('success' => 0, 'msg' => $errorMsg);
            echo json_encode($data);
        }
        else
        {
            $query = "INSERT INTO users (name, email, fname, lname, city, phone, password, role, active)
            VALUES ('".$uname."', '".$email."', '".$fname."', '".$lname."' , '".$city."', '".$phone."' , '".md5($password)."', '".$role."', 1)";

            $run = mysqli_query($conn, $query);

            if(isset($run)){

                $custID = $conn->insert_id;
                $custIDPopuplated = "GS".$conn->insert_id.rand(10,100);
                $custIDPopuplated = substr($custIDPopuplated,0,6);

                $query_update = "UPDATE users
                SET customer_id = '".$custIDPopuplated."'
                WHERE id = '".$custID."'
                ";
                $run2 = mysqli_query($conn, $query_update);
                
                $data = array('success' => 1, 'msg' => "Successfully Added !");
                echo json_encode($data);
            }else{
                $data = array('success' => 0, 'msg' => "Something went Wrong !");
                echo json_encode($data);
            }
        }
    }

    // UPDATE
    if(isset($_POST['admin-update-user']))  /* This will be the hidden field for all conditions*/
    {
        
        $user_id = $_POST['user_id'];
        $uname = $_POST['uname'];
        $role = $_POST['role'];

        $fname = $_POST['fname'];
        $lname = $_POST['lname'];

        $phone = $_POST['phone'];
        $city = $_POST['city'];

        $email = $_POST['email'];
        $password = $_POST['password'];

        if($password!=""){
            $passwordQuery = " ,password = '".md5($password)."' ";
        }else{
            $passwordQuery = " ";
        }


        // VALIDATIONS ___________________
        if($fname==""){
            echo json_encode(array('success' => 0, 'msg' => "First Name can not be empty")); die();
        }
        if($email==""){
            echo json_encode(array('success' => 0, 'msg' => "Email can not be empty")); die();
        }
        // VALIDATIONS ___________________

        $queryMatch = "SELECT * from users where email = '".$email."' AND id <> '".$user_id."' AND deleted <> 1 ";
        $dataMatch = mysqli_query($conn, $queryMatch);
        
        if($dataMatch->num_rows > 0)
        {
            $errorMsg = "Email Already registered by someone, Please try a different one";
            $data = array('success' => 0, 'msg' => $errorMsg);
            echo json_encode($data);
        }
        else
        {
         
            $query = "UPDATE users
                SET name = '".$uname."',
                email = '".$email."',
                fname = '".$fname."',
                lname = '".$lname."',
                city = '".$city."',
                phone = '".$phone."'
                ".$passwordQuery."
                WHERE id = '".$user_id."' 
                ";

            $run = mysqli_query($conn, $query);

            if(isset($run)){
                $data = array('success' => 1, 'msg' => "Successfully Updated !");
                echo json_encode($data);
            }else{
                $data = array('success' => 0, 'msg' => "Something went Wrong !");
                echo json_encode($data);
            }
        }
    }


    if(isset($_GET['user-delete-request'])){  /* This will be the hidden field for all conditions*/

        $id = $_GET['user_id'];

        $query_update = "UPDATE users
            SET deleted = '1'
            WHERE id = '".$id."'
            ";

        $run = mysqli_query($conn, $query_update);

        if($run){
            header("location: all-admins.php");
        }
            else{
            header("location: all-admins.php");
        }
    }

    // ADMIN USERS Functions _________________________


    // ADMIN FEEDBACK Functions _________________________

        if(isset($_GET['feedback-delete-request'])){  /* This will be the hidden field for all conditions*/

        $id = $_GET['feedback_id'];

        $query_update = "UPDATE feedbacks
            SET deleted = '1'
            WHERE id = '".$id."'
            ";

        $run = mysqli_query($conn, $query_update);

        if($run){
            header("location: feedbacks-by-stars.php");
        }
            else{
            header("location: feedbacks-by-stars.php");
        }
    }
    // ADMIN FEEDBACK Functions _________________________
?>