<?php

session_start();

include "../db.php";

date_default_timezone_set('Asia/Kolkata');

$currentTime = date('M j, Y g:i a');



// Check if form is submitted via POST

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Get the product ID and remarks from the form

    $pid = mysqli_real_escape_string($con, $_POST['pid']);

    $remarks = mysqli_real_escape_string($con, $_POST['remarks']);



    // Check if there is a previously uploaded document

    $query = "SELECT pFinalDocument, pClient FROM product WHERE pid = '$pid'";

    $result = mysqli_query($con, $query);



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

        $row = mysqli_fetch_assoc($result);

        $previousFile = $row['pFinalDocument'];



        // Unlink the previous file if it exists

        if (!empty($previousFile)) {

            $previousFilePath = '../upload/finalDoc/' . $previousFile;

            if (file_exists($previousFilePath)) {

                if (!unlink($previousFilePath)) {

                    $_SESSION['error'] = "Error deleting the previous file.";

                    header('Location: ../index.php');

                    exit;

                }

            }

        }



        $client = $row["pClient"];

        $user_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$client' ");

        if($user_row = mysqli_fetch_assoc($user_sql)){

            $ucontact = $user_row["ucontact"];

            $uname = $user_row["uname"];

            $uemail = $user_row["uemail"];

        }

    }



    // Check if a new file is uploaded

    if (isset($_FILES['docFile']) && $_FILES['docFile']['error'] === UPLOAD_ERR_OK) {

        $fileTmpPath = $_FILES['docFile']['tmp_name'];

        $fileName = $_FILES['docFile']['name'];

        $fileSize = $_FILES['docFile']['size'];

        $fileType = $_FILES['docFile']['type'];

        $fileNameCmps = explode(".", $fileName);

        $fileExtension = strtolower(end($fileNameCmps));



        // Allowed file types

        $allowedfileExtensions = array('pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png', 'webp');



        if (in_array($fileExtension, $allowedfileExtensions)) {

            // Set the upload folder

            $uploadFileDir = '../upload/finalDoc/';

            $newFileName = $pid . "_" . time() . "." . $fileExtension; // Unique file name

            $dest_path = $uploadFileDir . $newFileName;



            // Compress image if the file is an image

            if (in_array($fileExtension, ['jpg', 'jpeg', 'png', 'webp'])) {

                // Handle image compression

                $image = null;

                if ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {

                    $image = imagecreatefromjpeg($fileTmpPath);

                } elseif ($fileExtension === 'png') {

                    $image = imagecreatefrompng($fileTmpPath);

                } elseif ($fileExtension === 'webp') {

                    $image = imagecreatefromwebp($fileTmpPath);

                }



                if ($image) {

                    // Compress image (60% quality for JPEG, PNG and WEBP with lower quality)

                    if ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {

                        imagejpeg($image, $dest_path, 60);

                    } elseif ($fileExtension === 'png') {

                        imagepng($image, $dest_path, 8);

                    } elseif ($fileExtension === 'webp') {

                        imagewebp($image, $dest_path, 60);

                    }

                    imagedestroy($image); // Free up memory

                } else {

                    $_SESSION['error'] = "Error compressing image.";

                    header('Location: ../index.php');

                    exit;

                }

            } else {

                // If not an image, move the file to the destination folder

                if (!move_uploaded_file($fileTmpPath, $dest_path)) {

                    $_SESSION['error'] = "Error moving the file to the upload directory.";

                    header('Location: ../index.php');

                    exit;

                }

            }



            // Update the product table with the new document details

            $sql = "UPDATE product SET pFinalDocument = '$newFileName', pFinalRemark = '$remarks', pFinalUpDate = '$currentTime' WHERE pid = '$pid'";

            if (mysqli_query($con, $sql)) {

                // Send SMS

                $api_key = '45899D6EF8D236';

                $entity = '1501681760000015777';

                $contacts = $ucontact;

                $message = "Document is Uploaded. Download it from App.";

                $from = 'DXTECH';

                $sms_text = urlencode("$uname, Password to Recover your Account is $message. Do not share with anyone. DIGI X");



                // Submit to server

                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, "http://manage.sambsms.com/app/smsapi/index.php");

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

                curl_setopt($ch, CURLOPT_POST, 1);

                curl_setopt($ch, CURLOPT_POSTFIELDS, "key=$api_key&entity=$entity&tempid=1407173554566676394&campaign=0&routeid=7&type=text&contacts=$contacts&senderid=$from&msg=$sms_text");



                $smsResponse = curl_exec($ch);

                $curlError = curl_error($ch); // Check for curl errors

                curl_close($ch);



                if ($curlError) {

                    // Log or handle curl error

                    $_SESSION['error'] = "SMS API Error: $curlError";

                    header("Location: view-productList.php?pid=$pid");

                    exit;

                }



                if ($smsResponse) {

                    // Log SMS API response for debugging

                    file_put_contents('sms_log.txt', "SMS Response: $smsResponse\n", FILE_APPEND);

                }



                // On success, redirect with a success alert

                $_SESSION['success'] = "File successfully uploaded, previous document deleted, and database updated.";

                header("Location: view-productList.php?pid=$pid");

                exit;

            } else {

                // If there is a database error, set error message and redirect

                $_SESSION['error'] = "Error updating the database: " . mysqli_error($con);

                header('Location: ../index.php');

                exit;

            }

        } else {

            // If the file type is not allowed, redirect with an error

            $_SESSION['error'] = "Upload failed. Allowed file types: " . implode(', ', $allowedfileExtensions);

            header('Location: ../index.php');

            exit;

        }

    } else {

        // If no file is uploaded or there's an upload error

        $_SESSION['error'] = "No file uploaded or there was an error during the upload.";

        header('Location: ../index.php');

        exit;

    }

} else {

    // If the request method is not POST

    $_SESSION['error'] = "Invalid request method.";

    header('Location: ../index.php');

    exit;

}



mysqli_close($con);

?>