<?php
require '../config/db.php';
require '../config/function/function.php';
require '../EmailSender/EmailSender.php';
include './mailTemplate.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_shippingFORM'])) {
    // Clean input data
    $user_name = cleanInput($_POST['user_name']);
    $user_email = cleanInput($_POST['user_email']);
    $user_number = cleanInput($_POST['user_number']);
    $package_name = cleanInput($_POST['package_name']);
    $current_location = cleanInput($_POST['current_location']);
    $receiver_address = cleanInput($_POST['receiver_address']);
    $origin = cleanInput($_POST['origin']);
    $destination = cleanInput($_POST['destination']);
    $shipping_type = cleanInput($_POST['shipping_type']);
    $quality = cleanInput($_POST['quality']);
    $weight = cleanInput($_POST['weight']);
    $payment_mode = cleanInput($_POST['payment_mode']);
    $expected_delivery_date = cleanInput($_POST['expected_delivery_date']);
    $pickup_date = cleanInput($_POST['pickup_date']);
    $pickup_time = cleanInput($_POST['pickup_time']);
    $comment = cleanInput($_POST['comment']);
    $amount =  cleanInput($_POST['amount']);

    $status = 'pending';
    $package_image = ""; // default
    // ✅ Handle file upload
    if (isset($_FILES['package_image']) && $_FILES['package_image']['error'] === UPLOAD_ERR_OK) {
$uploadDir = __DIR__ . "/../uploads/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileTmpPath = $_FILES['package_image']['tmp_name'];
        $fileName = time() . "_" . basename($_FILES['package_image']['name']);
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        // Allowed file types
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($fileExt, $allowedExts)) {
            $destPath = $uploadDir . $fileName;
            if (move_uploaded_file($fileTmpPath, $destPath)) {
                $package_image = $fileName; // Save filename for DB
            }
        }
    }

    $url = $_SERVER['HTTP_REFERER'];
    $noError = true;
    $message = "";
    $type = "error";

    if (empty($user_name)) {
        $message = "Enter user name";
        $noError = false;
    }

    if (empty($user_email) || !filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
        $message = empty($user_email) ? "Enter your email address." : "Enter a valid email address.";
        $noError = false;
    } else {
        $user_email = strtolower($user_email);
    }

    if (empty($user_number) || !preg_match('/^\d{11}$/', $user_number)) {
        $message = empty($user_number) ? "Enter user number." : "Enter a valid 11-digit phone number.";
        $noError = false;
    }

    if (empty($package_name)) {
        $message = "Enter package name";
        $noError = false;
    }

    if (empty($current_location)) {
        $message = "Enter current location";
        $noError = false;
    }

    if (empty($receiver_address)) {
        $message = "Enter receiver address";
        $noError = false;
    }

    if (empty($origin)) {
        $message = "Enter origin";
        $noError = false;
    }

    if (empty($destination)) {
        $message = "Enter destination";
        $noError = false;
    }

    if (empty($shipping_type)) {
        $message = "Enter shipping type";
        $noError = false;
    }

    if (empty($quality)) {
        $message = "Enter quality";
        $noError = false;
    }
    if (empty($weight)) {
       $message = "Enter weight";
       $noError = false;
    }

    if (empty($payment_mode)) {
        $message = "Enter payment mode";
        $noError = false;
    }

    if (empty($expected_delivery_date)) {
        $message = "Enter expected delivery date";
        $noError = false;
    }

    if (empty($comment)) {
        $message = "Enter comment";
        $noError = false;
    }

    if (empty($amount)) {
        $message = "Enter amount";
        $noError = false;
    }


    if ($noError) {
        $unique_Id = date('YmdHis') . rand(100000, 999998);
        $trackNo = date('YmdHis') . rand(100000, 999999);
        $carrier_ref = date('YmdHis') . rand(1000, 9999);

        // Prepare SQL query
        // ✅ Update your INSERT query to include package_image
    $query = "INSERT INTO packages 
        (trackNo, unique_Id, user_name, user_email, user_number, package_name, current_location, receiver_address, origin, destination, shipping_type, quality, weight, payment_mode, expected_delivery_date, pickup_date, pickup_time, comment, carrier_ref, amount, status, package_image) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($query);

    if ($stmt) {
        $stmt->bind_param(
    "ssssssssssssssssssssss",
    $trackNo,
    $unique_Id,
    $user_name,
    $user_email,
    $user_number,
    $package_name,
    $current_location,
    $receiver_address,
    $origin,
    $destination,
    $shipping_type,
    $quality,
    $weight,
    $payment_mode,
    $expected_delivery_date,
    $pickup_date,
    $pickup_time,
    $comment,
    $carrier_ref,
    $amount,
    $status,
    $package_image
);
    


            // Execute the query
            if ($stmt->execute()) {
                // Fetch the inserted data
                $fetchQuery = "SELECT * FROM packages WHERE unique_Id = ?";
                $fetchStmt = $conn->prepare($fetchQuery);

                if ($fetchStmt) {
                    $fetchStmt->bind_param("s", $unique_Id);
                    $fetchStmt->execute();
                    $fetchResult = $fetchStmt->get_result();

                    if ($fetchResult && $fetchResult->num_rows > 0) {
                        $userData = $fetchResult->fetch_assoc();
                        $user_name = $userData['user_name'];
                        $trackNo = $userData['trackNo'];
                        $status = $userData['status'];
                        $amount = $userData['amount'];

                        // Store data in session
                        $_SESSION['unique_Id'] = $unique_Id;
                        $_SESSION['user_name'] = $user_name;

                        // Prepare email content with more details
                        $subject = 'Package Tracking Information';
                        $logoUrl = "https://swiftwaylog.org/assets/sww.png"; // change this to your actual logo file
                        $emailContent = "
                        <div class='email-container' style='font-family: Arial, sans-serif; color: #333;'>
                        <h3 style='color: #004080;'>Welcome to Swift Way Logistics, $user_name!</h3>
                        <p>Your package has been successfully registered. Below are the details of your shipment:</p>
                        
                        <table style='width: 100%; border-collapse: collapse; margin-bottom: 20px;'>
                            <tr>
                                <th style='text-align: left; padding: 8px; border: 1px solid #ddd; background-color: #f9f9f9;'>Field</th>
                                <th style='text-align: left; padding: 8px; border: 1px solid #ddd; background-color: #f9f9f9;'>Details</th>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Tracking Number</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$trackNo</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Package Name</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$package_name</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Origin</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$origin</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Destination</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$destination</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Shipping Type</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$shipping_type</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Quality</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$quality</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Weight</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$weight kg</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Payment Mode</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$payment_mode</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Expected Delivery Date</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>" . date('j F Y', strtotime($expected_delivery_date)) . "</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Pickup Date</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>" . date('j F Y', strtotime($pickup_date)) . "</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Pickup Time</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>" . date('h:i A', strtotime($pickup_time)) . "</td>
                            </tr>
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Comment</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>$comment</td>
                            </tr>
                            " . (!empty($package_image) ? "
                            <tr>
                                <td style='padding: 8px; border: 1px solid #ddd;'>Package Image</td>
                                <td style='padding: 8px; border: 1px solid #ddd;'>
                                    <img src='https://swiftwaylog.org/uploads/$package_image' alt='Package Image' style='max-width:250px; border:1px solid #ccc; border-radius:4px;'>
                                </td>
                            </tr>" : "") . "
                        </table>

                        
                        <p>To track the status of your package, simply click the link below:</p>
                        <p style='margin: 20px 0;'>
                            <a href='https://swiftwaylog.org/tracking?email=$user_email' 
                               style='background-color: #004080; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px;' 
                               target='_blank'>
                                Track Your Package
                            </a>
                        </p>
                        
                        <p>If the button above doesn't work, copy and paste the following link into your browser:</p>
                        <p style='color: #004080; word-break: break-all;'>https://swiftwaylog.org/tracking?email=$user_email</p>
                        
                        <p>For any inquiries or assistance, feel free to contact our support team at <a href='mailto:support@swiftwaylog.org' style='color: #004080;'>support@swiftwaylog.org</a>.</p>
                        
                        <p>Thank you for choosing Swift Way Logistics. We are committed to delivering your package safely and on time.</p>
                        
                        <p>Best regards,<br>Swift Way Logistics Team</p>
                        </div>
                        ";

                        $template = './mailTemplate.php';
                        try {
                            if (EmailSender::sendEmail($user_email, $user_name, $subject, $template, $emailContent)) {
                                redirectWithMessage($url, "Shipping successful. Email sent to $user_email", "success");
                            } else {
                                redirectWithMessage($url, "Shipping successful, but email sending failed.", "error");
                            }
                        } catch (Exception $e) {
                            redirectWithMessage($url, "Shipping successful, but email sending failed. Error: " . $e->getMessage(), "error");
                        }
                    } else {
                        $message = "Failed to fetch user data.";
                    }
                } else {
                    $message = "Database error. Please try again.";
                }
            } else {
                $message = "Shipping failed. Please try again.";
            }
        } else {
            $message = "Database error. Please try again.";
        }
    }

    redirectWithMessage($url, $message, $type);
}



if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_update_shipping'])) {
    $unique_Id = cleanInput($_POST['delivery_Id']);
    $current_location = cleanInput($_POST['current_location']);
    $receiver_address = cleanInput($_POST['receiver_address']);
    $expected_delivery_date = cleanInput($_POST['expected_delivery_date']);
    $pickup_date = cleanInput($_POST['pickup_date']);
    $pickup_time = cleanInput($_POST['pickup_time']);

    $url = $_SERVER['HTTP_REFERER'];
    $message = "";
    $type = "error";

    if (empty($unique_Id) || empty($current_location) || empty($receiver_address) || empty($expected_delivery_date) || empty($pickup_date) || empty($pickup_time)) {
        redirectWithMessage("$url", "All fields are required.", "error");
        exit();
    }

    // 🔹 Handle package image upload if provided
    $package_image = null; // default
    if (isset($_FILES['package_image']) && $_FILES['package_image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . "../uploads/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileTmpPath = $_FILES['package_image']['tmp_name'];
        $fileName = time() . "_" . basename($_FILES['package_image']['name']);
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif'];

        if (in_array($fileExt, $allowedExts)) {
            $destPath = $uploadDir . $fileName;
            if (move_uploaded_file($fileTmpPath, $destPath)) {
                $package_image = $fileName;

                // 🔹 Remove old image if exists
                $oldImgQuery = "SELECT package_image FROM packages WHERE unique_Id = ?";
                $oldImgStmt = $conn->prepare($oldImgQuery);
                $oldImgStmt->bind_param("s", $unique_Id);
                $oldImgStmt->execute();
                $oldResult = $oldImgStmt->get_result();
                if ($oldResult && $oldResult->num_rows > 0) {
                    $oldRow = $oldResult->fetch_assoc();
                    if (!empty($oldRow['package_image'])) {
                        $oldFilePath = $uploadDir . $oldRow['package_image'];
                        if (file_exists($oldFilePath)) {
                            unlink($oldFilePath);
                        }
                    }
                }
                $oldImgStmt->close();
            }
        }
    }

    // 🔹 Build dynamic SQL depending on whether an image is uploaded
    if ($package_image) {
        $query = "UPDATE packages SET current_location = ?, receiver_address = ?, expected_delivery_date = ?, pickup_date = ?, pickup_time = ?, package_image = ? WHERE unique_Id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("sssssss", $current_location, $receiver_address, $expected_delivery_date, $pickup_date, $pickup_time, $package_image, $unique_Id);
    } else {
        $query = "UPDATE packages SET current_location = ?, receiver_address = ?, expected_delivery_date = ?, pickup_date = ?, pickup_time = ? WHERE unique_Id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssssss", $current_location, $receiver_address, $expected_delivery_date, $pickup_date, $pickup_time, $unique_Id);
    }

    if ($stmt && $stmt->execute()) {
        // Fetch the updated user's data
        $fetchQuery = "SELECT * FROM packages WHERE unique_Id = ?";
        $fetchStmt = $conn->prepare($fetchQuery);

        if ($fetchStmt) {
            $fetchStmt->bind_param("s", $unique_Id);
            $fetchStmt->execute();
            $fetchResult = $fetchStmt->get_result();

            if ($fetchResult && $fetchResult->num_rows > 0) {
                $userData = $fetchResult->fetch_assoc();
                $user_name = $userData['user_name'];
                $user_email = $userData['user_email'];
                $expected_delivery_date = $userData['expected_delivery_date'];
                $pickup_date = $userData['pickup_date'];
                $pickup_time = $userData['pickup_time'];
                $trackNo = $userData['trackNo'];
                $status = $userData['status'];
                $package_image = $userData['package_image'];

                // Send email to user
                $subject = 'Swift Way Logistics | Shipping Location Updated';
                $emailContent = "
                        <title>Shipping Location Updated</title>
                        <div class='email-container'>
                            <h3>Hello $user_name,</h3>
                            <p>Your shipping location has been updated.</p>
                            <p>Current Location: $current_location</p>
                            <p>Expected Delivery Date: " . (!empty($expected_delivery_date) ? date('j F Y', strtotime($expected_delivery_date)) : 'Not set') . "</p>
                            <p>PickUp Date: " . (!empty($pickup_date) ? date('j F Y', strtotime($pickup_date)) : 'Not set') . "</p>
                            <p>PickUp Time: " . (!empty($pickup_time) ? date('h:i A', strtotime($pickup_time)) : 'Not set') . "</p>
                            <p>Tracking Number: $trackNo</p>
                            <p>Status: <strong class='status-$status'>$status</strong></p>" .
                            (!empty($package_image) ? "<p><img src='https://swiftwaylog.org/uploads/$package_image' alt='Package Image' style='max-width:250px;border:1px solid #ccc;border-radius:4px;'></p>" : "") .
                            "<p><a href='https://swiftwaylog.org/tracking?email=$user_email' target='_blank'>Track your package</a></p>
                            <br>
                            <p>Best regards,<br>Swift Way Logistics Team</p>
                        </div>
                        <style>
                            .email-container {
                                padding: 20px;
                                background-color: #f9f9f9;
                                border-radius: 10px;
                                box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
                                max-width: 600px;
                                margin: auto;
                            }
                            .email-container h3 { color: #333; }
                            .email-container p { color: #555; }
                            .email-container a {
                                background-color: blue;
                                color: white;
                                padding: 10px;
                                text-decoration: none;
                                border-radius: 5px;
                            }
                            .status-pending { color: orange; }
                            .status-processing { color: blue; }
                            .status-completed { color: green; }
                        </style>
                    ";

                $template = './mailTemplate.php';
                try {
                    if (EmailSender::sendEmail($user_email, $user_name, $subject, $template, $emailContent)) {
                        redirectWithMessage("$url", "Shipping location updated successfully. Email sent to $user_email", "success");
                    } else {
                        redirectWithMessage("$url", "Shipping updated, but email sending failed.", "error");
                    }
                } catch (Exception $e) {
                    redirectWithMessage("$url", "Shipping updated, but email failed. " . $e->getMessage(), "error");
                }
            } else {
                redirectWithMessage("$url", "Failed to fetch user data.", "error");
            }
        }
    } else {
        redirectWithMessage("$url", "Failed to update shipping location.", "error");
    }

    $conn->close();
}





if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_emailCONTACT']))
    $errors = [];

// Sanitize user inputs
$dname = $conn->real_escape_string(trim($_POST['dname']));
$demail = $conn->real_escape_string(trim($_POST['demail']));
$dsubject = $conn->real_escape_string(trim($_POST['dsubject']));
$dmessage = $conn->real_escape_string(trim($_POST['dmessage']));

$url = $_SERVER['HTTP_REFERER'];
$noError = true;
$location = "$url";
$message = "";
$type = "error";

// Validate inputs
if (empty($dname)) {
    $errors[] = "Name is required.";
}
if (empty($demail) || !filter_var($demail, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "A valid email is required.";
}
if (empty($dsubject)) {
    $errors[] = "Subject is required.";
}
if (empty($dmessage)) {
    $errors[] = "Message is required.";
}


if (empty($errors)) {
    // Insert into database
    $stmt = $conn->prepare("INSERT INTO contacts (dname, demail, dsubject, dmessage) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $dname, $demail, $dsubject, $dmessage);

    if ($stmt->execute()) {
        $toEmail = "sundaygift34@gmail.com";
        $email_message = "An email has been received with the following details:\n\n";
        $mailHeaders = "Name: $dname\r\n" .
            "Sender: $demail\r\n" .
            "Subject: $dsubject\r\n" .
            "Message: $dmessage\r\n";

        if (mail($toEmail, $email_message, $mailHeaders)) {
            $message = "Submitted successfully. Our agents will attend to you soon.";
            $message = "success";
        } else {
            $message = "Form submitted, but email sending failed.";
            $message = "error";
        }
    } else {
        $message = "Failed to save your data. Please try again later.";
        $message = "error";
    }

    $stmt->close();
} else {
    // Collect and display validation errors
    $message = implode("<br>", $errors);
    $message = "error";
} {
    $conn->close();
    redirectWithMessage($url, $message, $type);
    exit;
}
