<?php

// $sourceFileName = $_FILES["ent_logo"]["name"];
// $resizedImage = reduceImageQuality($sourceFilePath);
// $newFileUrl = uploadFileToSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $folderName, $sourceFileName, $resizedImage);

// if ($answer['status'] == "success" && $answer['type'] == "Updated" && $newFileUploaded == true) {

//     if (!empty($oldFileToDelete)) {

//         // DELETE FILE FROM DigitalOcean
//         // Parse the URL and get the path component
//         $parsedUrl = parse_url($oldFileToDelete);
//         $path = $parsedUrl['path'];
//         // Remove the leading slash from the path, if present
//         $finalFilePath = ltrim($path, '/');
//         deleteFileFromSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $finalFilePath);

//         // DELETE FILE FROM contabostorage
//         // Extract bucket identifier and bucket name from the URL
//         $pattern = "/https:\/\/{$awsRegion}.contabostorage.com\/([^:]+):([^\/]+)\/(.+)/";
//         if (preg_match($pattern, $oldFileToDelete, $matches)) {
//             $bucketIdentifier = $matches[1];
//             $bucketName = $matches[2];
//             $finalFilePath = $matches[3];
//             deleteFileFromSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $finalFilePath);
//         }
//     }
// }



// case 'sendTicketWhatsApp':

//     $imageData = $_POST["image"];
//     $sale_id = $_POST["sale_id"];
//     $toPhone = $_POST["toPhone"];
//     $entName = $_POST["entName"];
//     $replyTo = $_POST["replyTo"];
//     $pos_lang = $_POST["pos_lang"];

//     $imageData = str_replace('data:image/png;base64,', '', $imageData);
//     $imageData = str_replace(' ', '+', $imageData);
//     $decodedImage = base64_decode($imageData);
//     $caption = "*{$entName}* \n";

//     $posTranslate = getPosLanguage($pos_lang);

//     if (!empty($replyTo)) {
//         $caption .= "{$posTranslate['for_questions_or_complaints_contact_this_number']}: {$replyTo}";
//     }

//     $imageUrl = uploadFileToSpaceFromHtml2canvas($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $decodedImage, $sale_id);
//     $response = sendWhatsAppImage($toPhone, $imageUrl, $caption);
//     // echo $response;
//     echo json_encode($response);

//     break;



// SIMPLE WAY
// function SendWhatsAppTexts($phone, $message)
// {
//     $payload = [
//         "phone"   => preg_replace('/\D+/', '', $phone),
//         "body"    => $message,
//     ];

//     // Build URL with encoded JSON data
//     $endpoint = "http://127.0.0.1:3001/?" . http_build_query([
//         'type' => 'text',
//         'data' => json_encode($payload)
//     ]);

//     $response = file_get_contents($endpoint);

//     if ($response === false) {
//         return [
//             "status"  => "error",
//             "message" => "Request failed"
//         ];
//     }

//     return [
//         "status"   => "success",
//         "response" => json_decode($response, true)
//     ];
// }


// SIMPLE WAY
// function sendWhatsAppImages(string $phone, string $url, string $caption = ""): array
// {
//     $payload = [
//         "phone"   => preg_replace('/\D+/', '', $phone),
//         "body"    => $url,
//         "caption" => $caption,
//     ];

//     // Build URL with encoded JSON data
//     $endpoint = "http://127.0.0.1:3001/?" . http_build_query([
//         'type' => 'media',
//         'data' => json_encode($payload)
//     ]);

//     $response = file_get_contents($endpoint);

//     if ($response === false) {
//         return [
//             "status"  => "error",
//             "message" => "Request failed"
//         ];
//     }

//     return [
//         "status"   => "success",
//         "response" => json_decode($response, true)
//     ];
// }


// phone number in international format

// echo $resMsg = SendWhatsAppText("18098389538", "Test Message Text from WhatsApp Server");
// Group ID that I created by myself
// echo $resMsg = SendWhatsAppTextToGroup("18098389538-1501856522@g.us", "Test Message Text to Group from WhatsApp Server");

// Group ID that I'm in
// echo $resMsg = SendWhatsAppTextToGroup("120363342843157599@g.us", "Test Message Text to Group from WhatsApp Server");
// sendWhatsAppImage("18098389538", "http://127.0.0.1/ws/646fd5fcc938b.png");
// SendWhatsAppText($testPhone, $testMessage);




// CLOUDINARY 

// https://usc1.contabostorage.com/5adcb23ae613489a9fe4ad4a7bec3e6a:evosyspos-obs/laurie`s kitchen/users/68fd92c4c5c80.jpeg

// $entInfo
// $posInfo

// $oldFileToDelete = "https://res.cloudinary.com/itecevollc/image/upload/v1770615982/evosyspos/logos/69898394e2d6f.jpeg";
// $sourceFilePath = "../assets/images/69898394e2d6f.jpeg";
// $resourceType = "image";
// $saveToFolder = "evosyspos/{$entInfo['ent_folder_name']}/logos";
// $fileName = "";
// $oldFileToDelete = "";

// $resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, $resourceType = "image", $fileName = "", $oldFileToDelete = "");

// $public_id = $resCloudUpload['public_id'];
// $format = $resCloudUpload['format'];
// $resource_type = $resCloudUpload['resource_type'];
// $secure_url = $resCloudUpload['secure_url'];
// $secure_url = "https://res.cloudinary.com/itecevollc/image/upload/v1770615982/evosyspos/logos/69898394e2d6f.jpeg";

// $imageSize = "f_auto,q_auto,w_150,c_limit";
// $imageSize = "f_auto,q_auto,w_400,c_limit";
// $imageSize = "f_auto,q_auto,w_200,c_limit";
// $imageSize = "f_auto,q_auto,w_800,c_limit";

function getPublicId(string $secure_url, string $imageSize = "f_auto,q_auto,w_400,c_limit")
{
    return str_replace(
        '/image/upload/',
        '/image/upload/f_auto,q_auto,w_400,c_limit/',
        $secure_url
    );
}

function cloudinaryImageUrl(
    string $publicId,
    string $transform = 'f_auto,q_auto,w_400,c_limit',
    string $format = 'png',
    string $cloudName = 'itecevollc'
): string {
    return "https://res.cloudinary.com/{$cloudName}/image/upload/{$transform}/{$publicId}.{$format}";
}

// $resPublicId = getPublicId($secure_url, $imageSize);

// $publicId = 'evosyspos/logos/69897f7e6ddc9';

// cloudinaryImageUrl($publicId, 'f_auto,q_auto,w_150,c_limit');

// <img
// src="cloudinaryImageUrl($publicId, 'f_auto,q_auto,w_400,c_limit')"
//   srcset="
//     cloudinaryImageUrl($publicId, 'f_auto,q_auto,w_200,c_limit') 200w,
//     cloudinaryImageUrl($publicId, 'f_auto,q_auto,w_400,c_limit') 400w,
//     cloudinaryImageUrl($publicId, 'f_auto,q_auto,w_800,c_limit') 800w
//   "
//   sizes="(max-width: 600px) 90vw, 400px"
//   alt="Image"
// />

// https://res.cloudinary.com/itecevollc/image/upload/f_auto,q_auto,w_400,c_limit/evosyspos/logos/69898394e2d6f.jpeg


// echo '<pre>';
// echo json_encode(["url" => $resPublicId], JSON_PRETTY_PRINT);
// echo '</pre>';


// {
// "asset_id": "ec8964baf8cb1ee843675b869896e9b8",
// "public_id": "evosyspos/logos/69898394e2d6f",
// "version": 1770619803,
// "version_id": "f38cac97a56932050b45a8f4f05f0f38",
// "signature": "65ca43950d9551157252a58bf39fd01511898179",
// "width": 2800,
// "height": 2100,
// "format": "jpeg",
// "resource_type": "image",
// "created_at": "2026-02-09T06:50:03Z",
// "tags": [],
// "bytes": 6293475,
// "type": "upload",
// "etag": "c0806a65244745e69b5aba53e92b6c3f",
// "placeholder": false,
// "url": "http://res.cloudinary.com/itecevollc/image/upload/v1770619803/evosyspos/logos/69898394e2d6f.jpeg",
// "secure_url": "https://res.cloudinary.com/itecevollc/image/upload/v1770619803/evosyspos/logos/69898394e2d6f.jpeg",
// "asset_folder": "evosyspos/logos",
// "display_name": "69898394e2d6f",
// "original_filename": "outdoor-billboard-mockup",
// "api_key": "169783692913589"
// }

// CLOUDINARY



// require __DIR__ . '/vendor/autoload.php';

// use Mpdf\Mpdf;

// // ==============================
// // CONFIG
// // ==============================
// $resendApiKey = 'YOUR_RESEND_API_KEY';
// $fromEmail    = 'sender@example.com';   // Must be verified in Resend
// $toEmail      = 'recipient@example.com';

// // ==============================
// // 1. GENERATE PDF IN MEMORY
// // ==============================

// $mpdf = new Mpdf();

// $html = '
// <h1>Hello from mPDF!</h1>
// <p>This PDF was generated in memory and sent using Resend API.</p>
// <p>Date: ' . date('Y-m-d H:i:s') . '</p>
// ';

// $mpdf->WriteHTML($html);

// // Save PDF temporarily
// // $pdfFilePath = __DIR__ . '/temp.pdf';
// // $mpdf->Output($pdfFilePath, \Mpdf\Output\Destination::FILE);
// // // Read file and encode in base64
// // $pdfContent = base64_encode(file_get_contents($pdfFilePath));


// // Output PDF as STRING (no file saved)
// $pdfString = $mpdf->Output('', \Mpdf\Output\Destination::STRING_RETURN);

// // Base64 encode for Resend attachment
// $pdfBase64 = base64_encode($pdfString);

// // ==============================
// // 2. SEND EMAIL VIA RESEND API
// // ==============================

// $data = [
//     "from" => $fromEmail,
//     "to" => [$toEmail],
//     "subject" => "Your PDF File",
//     "html" => "<p>Please find the attached PDF generated in memory.</p>",
//     "attachments" => [
//         [
//             "filename" => "document.pdf",
//             "content"  => $pdfBase64
//         ]
//     ]
// ];

// $ch = curl_init("https://api.resend.com/emails");

// curl_setopt_array($ch, [
//     CURLOPT_RETURNTRANSFER => true,
//     CURLOPT_POST => true,
//     CURLOPT_HTTPHEADER => [
//         "Authorization: Bearer $resendApiKey",
//         "Content-Type: application/json"
//     ],
//     CURLOPT_POSTFIELDS => json_encode($data)
// ]);

// $response = curl_exec($ch);
// $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// curl_close($ch);

// // ==============================
// // RESULT
// // ==============================

// if ($httpCode === 200) {
//     echo "Email sent successfully!";
// } else {
//     echo "Failed to send email. Response: " . $response;
// }



// function sendSalesReport($appURL)
// {
//     try {

//         $client = new Client([
//             'base_uri' => rtrim($appURL, '/') . '/',
//             // 'base_uri' => $appURL,
//             'timeout'  => 60,
//         ]);


//         $sqlEnterprise = "SELECT ent_id FROM tb_enterprises WHERE ent_email_report = 'Enabled' AND ent_status = 'Enabled' ORDER BY ent_id ASC;";
//         $entInfo = executePDOFetchAllAPI($sqlEnterprise);

//         if ($entInfo['status'] === "success") {

//             $entData = $entInfo['data'];

//             foreach ($entData as $enterprise) {
//                 $entId = $enterprise['ent_id'];

//                 $sqlUser = "SELECT user_branch_access FROM tb_users WHERE user_ent_id = {$entId} AND user_email_report = 'Enabled' ORDER BY user_id ASC;";
//                 $userInfo = executePDOFetchAllAPI($sqlUser);

//                 if ($userInfo['status'] === "success") {
//                     $userData = $userInfo['data'];

//                     foreach ($userData as $user) {

//                         $userBranchAccess = $user['user_branch_access'];
//                         $userBranchAccess = json_decode($userBranchAccess, true);
//                         $userBranchAccess = array_column($userBranchAccess, 'pos_id');

//                         $attachments = [];

//                         foreach ($userBranchAccess as $branchId) {

//                             $payload = [
//                                 "ent"     => "2",
//                                 "pos"  => $branchId,
//                                 "from"    => "2026-02-22",
//                                 "to"      => "2026-02-22",
//                                 "groupBy" => "day",
//                                 "purpose" => "email",
//                             ];

//                             $response = $client->get('/reports/sales-report/index.php', [
//                                 'query'  => $payload,
//                                 'stream' => true,
//                             ]);

//                             $stream = $response->getBody();

//                             $jsonBuffer = '';
//                             while (!$stream->eof()) {
//                                 $jsonBuffer .= $stream->read(8192);
//                             }

//                             $data = json_decode(trim($jsonBuffer), true);

//                             if (
//                                 json_last_error() !== JSON_ERROR_NONE ||
//                                 empty($data['filename']) ||
//                                 empty($data['content'])
//                             ) {
//                                 throw new \Exception("Invalid PDF for branch {$branchId}");
//                             }

//                             $attachments[] = [
//                                 'filename' => $data['filename'],
//                                 'content'  => $data['content'],
//                                 'type'     => $data['type'] ?? 'application/pdf'
//                             ];
//                         }

//                         // Send ONE email with ALL branch attachments
//                         return sendEmail(
//                             "jackson@itecevo.com",
//                             "Daily Sales Report - All Branches",
//                             "<p>Please find attached daily sales reports for all branches.</p>",
//                             "support@itecevo.com",
//                             [],
//                             [],
//                             $attachments
//                         );
//                     }
//                 } else {
//                     throw new \Exception("No users found with email reports enabled for enterprise ID {$entId}.");
//                 }
//             }
//         } else {
//             throw new \Exception("No enterprises found with email reports enabled.");
//         }
//     } catch (ConnectException $e) {
//         return ["status" => "error", "message" => $e->getMessage()];
//     } catch (RequestException $e) {
//         return ["status" => "error", "message" => $e->getMessage()];
//     } catch (\Throwable $e) {
//         return ["status" => "error", "message" => $e->getMessage()];
//     }
// }

try {

    $pdo->beginTransaction();

    $isNew = empty(trim($sale_type_id));

    if ($isNew) {

        $response = array("message" => $translate['saved_successfully'], "status" => "success");
    } else {

        $response = array("message" => $translate['updated_successfully'], "status" => "success");
    }

    $pdo->commit();
} catch (\RuntimeException | \InvalidArgumentException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
} catch (\PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
}

echo json_encode($response);
