<?php
header('Access-Control-Allow-Origin: *');
header(
    'Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS'
);
header(
    'Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization'
);
header('Content-Type: application/json');

require '../../../../mail/libs/Exception.php';
require '../../../../mail/libs/PHPMailer.php';
require '../../../../mail/libs/SMTP.php';

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

include '../../../../config/db.php';
$image = "";
$orderNumber = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'));
    if (
        !empty($data->serviceId) &&
        !empty($data->amount) &&
        !empty($data->firstName) &&
        !empty($data->lastName) &&
        !empty($data->businessName) &&
        !empty($data->businessCategory) &&
        !empty($data->businessAddress) &&
        !empty($data->phone)
    ) {
        //order save data
        $today = date("Y-m-d");
        $tomorrow = date("Y-m-d", strtotime($today . " +1 day"));
        $orderCountQuery = "SELECT COUNT(*) FROM Orders WHERE dateCreated BETWEEN '$today' AND '$tomorrow'";
        $orderCountResult = mysqli_query($con, $orderCountQuery);
        $orderCountToday = mysqli_fetch_assoc($orderCountResult)["COUNT(*)"];
        $orderCountToday = $orderCountToday + 1;
        $serviceId = mysqli_real_escape_string($con, $data->serviceId);
        $orderPrefix = substr(date("Ymd"), 2);
        $orderNumber = $orderPrefix . '-' . $orderCountToday;
        $userId = mysqli_real_escape_string($con, $data->userId);
        $famId = mysqli_real_escape_string($con, $data->famId);
        $amount = mysqli_real_escape_string($con, $data->amount);
        $email = mysqli_real_escape_string($con, $data->email);
        $slipType = (isset($data->slipType)) ? mysqli_real_escape_string($con, $data->slipType) : '';
        $paymentMethod = (isset($data->paymentMethod)) ? mysqli_real_escape_string($con, $data->paymentMethod) : 0;
        $paymentAddress =  (isset($data->paymentAddress)) ? mysqli_real_escape_string($con, $data->paymentAddress) : "";
        $paymentCountry = (isset($data->paymentCountry)) ? mysqli_real_escape_string($con, $data->paymentCountry) : "";
        $paymentCity = (isset($data->paymentCity)) ? mysqli_real_escape_string($con, $data->paymentCity) : "";
        // $image = $data->image ? $data->image : '';
        $dateTime = date("Y-m-d H:i:s");

        //brand name order save data
        $fName = mysqli_real_escape_string($con, $data->firstName);
        $lName = mysqli_real_escape_string($con, $data->lastName);
        $phone = mysqli_real_escape_string($con, $data->phone);
        $businessName = mysqli_real_escape_string($con, $data->businessName);
        $businessCategory = mysqli_real_escape_string($con, $data->businessCategory);
        $businessAddress = mysqli_real_escape_string($con, $data->businessAddress);
        $businessEmail = mysqli_real_escape_string($con, $data->businessEmail);
        $colors = mysqli_real_escape_string($con, $data->colors);
        $links = mysqli_real_escape_string($con, $data->links);
        $notes = mysqli_real_escape_string($con, $data->notes);
        $prevGraphics = $data->prevGraphics ? $data->prevGraphics : "";
        $prevGraphicsType = $data->prevGraphicsType ? $data->prevGraphicsType : "";

        $query_1 = "INSERT INTO `Orders`(`orderId`,`serviceId`, `orderNumber`, `userId`, `famId`, `amount`, `paymentStatus`, `paymentMethod`, `paymentAddress`, `paymentCountry`, `paymentCity`, `status`, `dateCreated`, `dateModified`)
         VALUES (null,$serviceId,'$orderNumber','$userId','$famId','$amount',0, '$paymentMethod' ,'$paymentAddress','$paymentCountry','$paymentCity',1,'$dateTime','$dateTime')";
        if (mysqli_query($con, $query_1)) {
            if (mysqli_affected_rows($con) == 1) {
                $orderId = $con->insert_id;

                $query_2 = "INSERT INTO `BrandingOrders`(`brandOrderId`, `orderId`, `fName`, `lName`, `email`, `phone`, `businessName`, `businessCategory`, `businessAddress`, `businessEmail`, `colors`, `links`, `notes`, `status`, `dateCreated`, `dateModified`)
                VALUES (null,$orderId,'$fName','$lName','$email','$phone','$businessName','$businessCategory','$businessAddress','$businessEmail','$colors','$links','$notes',1,'$dateTime','$dateTime')";

                if (mysqli_query($con, $query_2)) {
                    if (mysqli_affected_rows($con) == 1) {
                        $orderId2 = $con->insert_id;
                        if ($prevGraphics != "") {
                            $ext = ($prevGraphicsType == 'image/jpeg') ? '.png' : (($prevGraphicsType == 'application/pdf') ? '.pdf' : '.png');

                            $folderPath = "../../../../public/orders/";
                            $image_parts = explode(";base64,", $prevGraphics);
                            $image_type_aux = explode("image/", $image_parts[0]);
                            $image_base64 = base64_decode($image_parts[1]);
                            $imageName =  uniqid() . $ext;
                            $file = $folderPath . $imageName;
                            if (file_put_contents($file, $image_base64)) {
                                $query_3 = "UPDATE `BrandingOrders` SET `prev_graphics`= '$imageName' WHERE brandOrderId= '$orderId2'";
                                if (mysqli_query($con, $query_3)) {
                                    if (mysqli_affected_rows($con) == 1) {
                                        send_email_invoice($orderNumber, $email);
                                        echo json_encode([
                                            'status' => 1,
                                            'data' => $orderNumber,
                                            'message' => 'Data added successfully.',
                                        ]);
                                        http_response_code(200);
                                    }
                                } else {
                                    echo json_encode([
                                        'status' => -3,
                                        'data' => $orderNumber,
                                        'message' => 'Data added successfully. But image save failed.',
                                    ]);
                                    http_response_code(200);
                                }
                            } else {
                                echo json_encode([
                                    'status' => 2,
                                    'data' => $orderNumber,
                                    'message' => 'Data added successfully. But image save failed.',
                                ]);
                                http_response_code(200);
                            }
                        } else {
                            send_email_invoice($orderNumber, $email);
                            echo json_encode([
                                'status' => 1,
                                'data' => $orderNumber,
                                'message' => 'Data added successfully.',

                            ]);
                            http_response_code(200);
                        }
                    } else {
                        deleteOrder($con, $orderId);
                        echo json_encode([
                            'status' => 0,
                            'message' => 'Could not insert data.'
                        ]);
                        http_response_code(400);
                    }
                } else {
                    deleteOrder($con, $orderId);
                    echo json_encode([
                        'status' => 0,
                        'message' => 'Could not insert data.',
                    ]);
                    http_response_code(400);
                }
            } else {
                echo json_encode([
                    'status' => 0,
                    'message' => 'Could not insert data.',
                ]);
                http_response_code(200);
            }
        } else {
            echo json_encode([
                'status' => 0,
                'message' => mysqli_error($con),
            ]);
            http_response_code(200);
        }
    } else {
        echo json_encode([
            'status' => -1,
            'message' => 'Required fields are missing',
        ]);
        http_response_code(200);
    }
} else {
    echo json_encode([
        'status' => 0,
    ]);
    http_response_code(200);
}

function deleteOrder($con, $id)
{
    $delete_query = "DELETE FROM Orders WHERE OrderId= $id";
    mysqli_query($con, $delete_query);
}

function send_email_invoice($orderNumber, $toEmail)
{
    $ayushSendEmail = "technical@ayushnames.com";
    $ayushSendEmailPassword = 'Ayush@2022';
    $myPersonalEmail = $toEmail;

    $reply_email = 'info@ayushnames.com';

    $mail = new PHPMailer(true);
    $mail->SMTPDebug = 0;
    $mail->Host = 'ftp.ayushnames.com';
    $mail->SMTPAuth = true;
    $mail->Username = $ayushSendEmail;
    $mail->Password = $ayushSendEmailPassword;
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom($ayushSendEmail, 'Ayush Names - Order #' . $orderNumber);
    $mail->addAddress($myPersonalEmail);
    $mail->addReplyTo($reply_email, 'Ayush Names');
    $mail->isHTML(true);
    $mail->Subject = 'Ayush Names - Order confirmation - ' . $orderNumber;

    $txt = '<div style="margin-left: auto;margin-right: auto;width: 55%;">
                <div style="border: 0.5px solid #d7d7d7;border-radius: 10px;padding: 20px;width: fit-content;font-family: system-ui;">
                    <div style="width: 50%;">
                        <img style="height: auto; width: 50px;" src="https://ayushnames.com/assets/images/logo.png">
                    </div>
                    <p>Dear Customer,</p>
                    <p> Your order has been created successfully. Your order id is #' . $orderNumber . '.<br>An agent will contact you soon.</p>
                    <p>If you have any inquiry, please contact us by +94 77 456 3303 via Call or Whatsapp.</p>
                    <p> Thank you,</p>
                    <p>Ayush team</p>
                </div>
            </div>';

    $mail->Body = $txt;

    try {

        $mail->send();

        return true;
    } catch (Exception $e) {
        return false;
    }
}
