<?php
session_start();
include "../db.php";
date_default_timezone_set('Asia/Kolkata');
$currentTime = date('M j, Y g:i a');

// Include PHPMailer files
require_once '../PHPMailer/src/Exception.php';
require_once '../PHPMailer/src/PHPMailer.php';
require_once '../PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 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'];
        $pClient = $row['pClient'];

        // Unlink the previous file if it exists
        if (!empty($previousFile)) {
            $previousFilePath = '../upload/finalDoc/' . $previousFile;
            if (file_exists($previousFilePath)) {
                unlink($previousFilePath);
            }
        }

        $client_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$pClient'");
        if ($client_row = mysqli_fetch_assoc($client_sql)) {
            $uname = $client_row["uname"];
            $uemail = $client_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', 'xls', 'xlsx');

        if (in_array($fileExtension, $allowedfileExtensions)) {
            // Set the upload folder
            $uploadFileDir = '../upload/finalDoc/';
            $newFileName = $pid . "_" . time() . "." . $fileExtension;
            $dest_path = $uploadFileDir . $newFileName;

            // Move file or compress image
            if (in_array($fileExtension, ['jpg', 'jpeg', 'png', 'webp'])) {
                $image = null;
                if ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {
                    $image = imagecreatefromjpeg($fileTmpPath);
                } elseif ($fileExtension === 'png') {
                    $image = imagecreatefrompng($fileTmpPath);
                } elseif ($fileExtension === 'webp') {
                    $image = imagecreatefromwebp($fileTmpPath);
                }

                if ($image) {
                    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);
                } else {
                    $_SESSION['error'] = "Error compressing image.";
                    header('Location: ../index.php');
                    exit;
                }
            } else {
                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
            $sql = "UPDATE product SET pFinalDocument = '$newFileName', pFinalRemark = '$remarks', pFinalUpDate = '$currentTime' WHERE pid = '$pid'";
            if (mysqli_query($con, $sql)) {
                // Initialize PHPMailer
                $mail = new PHPMailer(true);

                try {
                    // SMTP Configuration
                    $mail->isSMTP();
                    $mail->Host = 'ayushlpo.com';
                    $mail->SMTPAuth = true;
                    $mail->Username = 'contact@ayushlpo.com';
                    $mail->Password = 'cKIcxib89a0R';
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                    $mail->Port = 587;

                    // Email Settings
                    $mail->setFrom('contact@ayushlpo.com', 'Ayush LPO');
                    $mail->addAddress($uemail, $uname);

                    // Attach the uploaded file
                    $mail->addAttachment($dest_path, $fileName);

                    // Email Content
                    $mail->isHTML(true);
                    $mail->Subject = 'Document Update Notification';
                    $mailBody = "
                        <h3>Dear $uname,</h3>
                        <p>The document has been successfully uploaded. You can download the document from the email or by logging into your profile.</p>";
                        if (!empty($remarks)) {
                            $mailBody .= "<p><strong>Remarks:</strong> $remarks</p>";
                        }
                        $mailBody .= "
                            <p>Best regards,<br>Ayush LPO</p>
                        ";
                        $mail->Body = $mailBody;

                    $mail->send();
                    $_SESSION['success'] = "File successfully uploaded and emailed.";
                    header("Location: view-productList.php?pid=$pid");
                    exit;
                } catch (Exception $e) {
                    error_log("Mailer Error: " . $mail->ErrorInfo);
                    $_SESSION['success'] = "File successfully uploaded. Email could not be sent.";
                    header("Location: view-productList.php?pid=$pid");
                    exit;
                }
            } else {
                $_SESSION['error'] = "Error updating the database: " . mysqli_error($con);
                header('Location: ../index.php');
                exit;
            }
        } else {
            $_SESSION['error'] = "Upload failed. Allowed file types: " . implode(', ', $allowedfileExtensions);
            header('Location: ../index.php');
            exit;
        }
    } else {
        $_SESSION['error'] = "No file uploaded or there was an error during the upload.";
        header('Location: ../index.php');
        exit;
    }
} else {
    $_SESSION['error'] = "Invalid request method.";
    header('Location: ../index.php');
    exit;
}

mysqli_close($con);
?>