<?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->paymentAddress) &&
        // !empty($data->paymentCountry) &&
        // !empty($data->paymentCity)
    ) {
        $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;
        // $orderNumber = random_int(1000, 9999);
        $userId = mysqli_real_escape_string($con, $data->userId);
        $amount = mysqli_real_escape_string($con, $data->amount);
        $paymentMethod = mysqli_real_escape_string($con, $data->paymentMethod);
        $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;
        $dateTime = date("Y-m-d H:i:s");

        $query = "INSERT INTO `Orders`(`orderId`,`serviceId`, `orderNumber`, `userId`, `amount`, `paymentStatus`, `paymentMethod`, `paymentAddress`, `paymentCountry`, `paymentCity`, `status`, `dateCreated`, `dateModified`)
         VALUES (null,$serviceId,'$orderNumber','$userId','$amount',0, '$paymentMethod' ,'$paymentAddress','$paymentCountry','$paymentCity',1,'$dateTime','$dateTime')";
        if (mysqli_query($con, $query)) {
            if (mysqli_affected_rows($con) == 1) {
                if($image != ""){
                    $orderId = $con->insert_id;
                    $folderPath = "../../../../public/orders/";
                    $image_parts = explode(";base64,", $image);
                    $image_type_aux = explode("image/", $image_parts[0]);
                    $image_base64 = base64_decode($image_parts[1]);
                    $imageName =  uniqid() . '.png';
                    $file = $folderPath . $imageName;
                    if (file_put_contents($file, $image_base64)) {
                        $query = "UPDATE `Orders` SET `image`= '$imageName' WHERE orderId= '$orderId'";
                        if (mysqli_query($con, $query)) {
                            if (mysqli_affected_rows($con) == 1) {
                                // send_email_invoice($orderNumber);
                                echo json_encode([
                                    'status' => 1,
                                    'data' =>  $orderId,
                                    'message' => 'Data added successfully.',
                                ]);
                                http_response_code(200);
                            }
                        }else{
                            echo json_encode([
                                'status' => -3,
                                'message' => 'Image name update failed.',
                            ]);
                            http_response_code(200);
                        }
                    }else{
                        echo json_encode([
                            'status' => 2,
                            'message' => 'Data added successfully. But image save failed.',
                        ]);
                        http_response_code(200);
                    }   
                }
                // else{
                //     send_email_invoice($orderNumber);
                //     echo json_encode([
                //         'status' => 1,
                //         'data' =>  $con->insert_id,
                //         'message' => 'Data added successfully.',
    
                //     ]);
                //     http_response_code(200);   
                // }
            } 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 send_email_invoice($orderNumber){
    $ayushSendEmail = "technical@ayushnames.com";
    $ayushSendEmailPassword = 'Ayush@2022';
    $myPersonalEmail = $request->email;


    $name =  $request->name;
    $email = $request->email;
    $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 - Verify My Account'.$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 Nimesh Nishara,</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;
    }

}