<?php

//Daily Auto Task Each 07:00:00 AM
// /usr/local/bin/php /home/evosyspos/public_html/app.evosyspos.com/models/AutoTaskSendEmailReport.php
// curl -s https://app.evosyspos.com/models/AutoTaskSendEmailReport.php

require __DIR__ . '/../vendor/autoload.php';
require_once "Operations.php";

use Dotenv\Dotenv;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ConnectException;

// Load the .env file
$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

date_default_timezone_set("America/New_York");

// file_put_contents(__DIR__ . '/crons.log', "Read ENV: " . date('Y-m-d H:i:s') . " " . json_encode($_ENV) . "\n", FILE_APPEND);

// Build dynamic URLs (e.g., for local and production environments)
$scheme = 'http';
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
    $_SERVER['SERVER_PORT'] == 443
) {
    $scheme = 'https';
}
// $appURL = "https://evosyspos.com";
$appURL = $scheme . '://' . $_SERVER['HTTP_HOST'];


// 📧 Function to send email using Resend API
function sendEmailReport($send_to, $subject, $htmlBody = "", $reply_to = "", $cc = [], $bcc = [], $fileAttachments = null)
{
    $resend = Resend::client($_ENV['RESEND_ACCESS_KEY']);

    try {
        // Prepare the basic email data
        $emailData = [
            'from' => "no-reply@{$_ENV['PRODUCT_DOMAIN']}", // Get domain from environment variables
            'to' => $send_to, // Array of recipients
            'reply_to' => $reply_to, // Reply-to address
            'subject' => $subject, // Subject of the email
            'html' => $htmlBody, // HTML body content
        ];

        // Add CC if provided
        if (!empty($cc)) {
            $emailData['cc'] = $cc;  // CC recipients
        }

        // Add BCC if provided
        if (!empty($bcc)) {
            $emailData['bcc'] = $bcc;  // BCC recipients
        }

        // ✅ MULTIPLE ATTACHMENTS SUPPORT
        if (!empty($fileAttachments) && is_array($fileAttachments)) {

            $emailData['attachments'] = [];

            foreach ($fileAttachments as $attachment) {

                if (
                    empty($attachment['filename']) ||
                    empty($attachment['content'])
                ) {
                    throw new \Exception("Invalid attachment format.");
                }

                $emailData['attachments'][] = [
                    'filename' => $attachment['filename'],
                    'content'  => $attachment['content'], // already base64
                    'type'     => $attachment['type'] ?? 'application/octet-stream',
                ];
            }
        }

        // Send email via Resend API
        $result = $resend->emails->send($emailData);

        $response = array("emailId" => $result, "status" => "success", "title" => "Success", "message" => "Email sent successfully");
        return $response;  // Return result if successful

    } catch (\Exception $e) {
        // Handle exceptions and errors
        $response = array("status" => "error", "title" => "Error", "message" => "Email could not be sent", "error" => "Error: " . $e->getMessage() . "");
        return $response;
    }
}


function sendSalesReport($appURL)
{
    $results = [
        'status'   => [],
        'sent'     => 0,
        'messages' => [],
        'errors'   => []
    ];

    try {

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

        // 1️⃣ Get enterprises
        $sqlEnterprise = "
            SELECT ent_id 
            FROM tb_enterprises 
            WHERE ent_email_report = :enabled 
            AND ent_status = :status
            ORDER BY ent_id ASC
        ";

        $entInfo = executePDOFetchAllAPI($sqlEnterprise, [
            ':enabled' => 'Enabled',
            ':status'  => 'Enabled'
        ]);

        if ($entInfo['status'] !== "success" || empty($entInfo['data'])) {
            return [
                "status" => "error",
                "message" => "No enterprises found with email reports enabled."
            ];
        }

        foreach ($entInfo['data'] as $enterprise) {

            $entId = (int)$enterprise['ent_id'];

            // 2️⃣ Get users per enterprise
            $sqlUser = "
                SELECT CONCAT(user_firstname,' ',user_lastname) AS user_full_name, user_email, user_branch_access
                FROM tb_users
                WHERE user_ent_id = :entId
                AND user_email_report = :enabled
                ORDER BY user_id ASC
            ";

            $userInfo = executePDOFetchAllAPI($sqlUser, [
                ':entId'  => $entId,
                ':enabled' => 'Enabled'
            ]);

            if ($userInfo['status'] !== "success" || empty($userInfo['data'])) {
                continue; // Skip enterprise instead of throwing
            }

            foreach ($userInfo['data'] as $user) {

                $attachments = [];

                $branchAccess = json_decode($user['user_branch_access'], true);

                if (!is_array($branchAccess)) {
                    $results['errors'][] = "Invalid branch access JSON for enterprise {$entId}";
                    continue;
                }

                $branchIds = array_column($branchAccess, 'pos_id');

                foreach ($branchIds as $branchId) {

                    // 1️⃣ Get Branch info
                    $sqlBranch = "
                        SELECT pos_id,pos_time_zone,pos_day_start_time,pos_day_end_time 
                        FROM tb_pos 
                        WHERE pos_id = :branchId 
                        AND pos_status = :status
                        ORDER BY pos_id ASC
                    ";

                    $branchInfo = executePDOFetchOneAPI($sqlBranch, [
                        ':branchId' => $branchId,
                        ':status'  => 'Enabled'
                    ]);

                    if ($branchInfo['status'] !== "success" || empty($branchInfo['data'])) {
                        $results['errors'][] = "Branch ID {$branchId} not found or not enabled for enterprise {$entId}";
                        continue; // Skip branch instead of throwing
                    }

                    $branchId = $branchInfo['data']['pos_id'];
                    $timeZone = $branchInfo['data']['pos_time_zone'] ?? "America/New_York";
                    $timeStart = $branchInfo['data']["pos_day_start_time"] ?? "07:00:00";
                    $timeEnd = $branchInfo['data']["pos_day_end_time"] ?? "06:59:59";

                    date_default_timezone_set($timeZone);

                    $yesterdayStart  = date("Y-m-d {$timeStart}", strtotime("-1 day"));
                    $yesterdayEnd = date("Y-m-d {$timeEnd}");

                    try {

                        $payload = [
                            "ent"     => $entId,
                            "pos"     => $branchId,
                            "from"    => $yesterdayStart,
                            "to"      => $yesterdayEnd,
                            "groupBy" => "day",
                            "purpose" => "email",
                        ];

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

                        $data = json_decode((string) $response->getBody(), true);

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

                        $attachments[] = [
                            'filename' => $data['filename'],
                            'content'  => $data['content'],
                            'type'     => $data['type'] ?? 'application/pdf'
                        ];
                    } catch (\Throwable $e) {
                        $results['errors'][] = "Enterprise {$entId}, Branch {$branchId}: " . $e->getMessage();
                    }
                }

                $userEmail = trim($user['user_email'] ?? '');

                if (!empty($attachments) && filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {

                    $emailResult = sendEmailReport(
                        $userEmail,
                        "Daily Sales Report - All Branches",
                        "<p>Please find attached daily sales reports for all branches.</p>",
                        "support@{$_ENV['COMPANY_DOMAIN']}",
                        [],
                        [],
                        $attachments
                    );

                    if (is_string($emailResult)) {
                        $emailResult = json_decode($emailResult, true);
                    }

                    if (is_array($emailResult) && ($emailResult['status'] ?? null) === 'success') {
                        $results['sent']++;

                        $emailId = $emailResult['emailId']['id'] ?? 'N/A';

                        $results['status'][] = "success";
                        $results['messages'][] = "Email sent to {$userEmail} (ID: {$emailId})";
                    } else {
                        $results['status'][] = "error";
                        $results['errors'][] = "Failed sending email to {$userEmail}: " . ($emailResult['message'] ?? 'Unknown error');
                    }
                } else {

                    $reason = empty($attachments) ? 'No attachments generated' : 'Invalid or empty email address';

                    $results['status'][] = "error";
                    $results['errors'][] = "Skipped user: {$user['user_full_name']}, email: {$userEmail}, Reason: {$reason}";
                }
            }
        }

        return $results;
    } catch (ConnectException | RequestException $e) {
        return ["status" => "error", "message" => $e->getMessage()];
    } catch (\Throwable $e) {
        return ["status" => "error", "message" => $e->getMessage()];
    }
}

$response = sendSalesReport($appURL);
// echo json_encode($response);

// file_put_contents(__DIR__ . '/crons.log', "Daily Auto Task Response: AutoTaskSendEmailReport: " . date('Y-m-d H:i:s') . " " . json_encode($response) . "\n", FILE_APPEND);
