<?php
    error_reporting(E_ALL);
    // ini_set('display_errors', 1);

    session_start();
    require_once '../connect.php';

    require_once './mailer/vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    header('Content-Type: application/json');

    $_POST = array_merge($_POST, (array) json_decode(file_get_contents('php://input'), true));

    $action = $_POST['action'] ?? '';

    switch ($action) {
        case 'send': sendMessage(); break;
        case 'log':  logOnly();     break;
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }

    // ------------------------------------------------------------------
    // SEND  — used by WhatsApp and Email (PHP handles the actual sending)
    // ------------------------------------------------------------------
    function sendMessage() {
    global $conn;
    $target_type = $_POST['target_type'] ?? '';
    $permPage = ($target_type === 'lead') ? 'leads' : 'customers';
    requirePermission($conn, $permPage, $permPage === 'leads' ? 'take_action' : 'message');
        $type        = $_POST['type']        ?? '';
        $customer_id = intval($_POST['customer_id'] ?? 0);
        $subject     = sanitize($GLOBALS['conn'], $_POST['subject'] ?? '');
        $message     = sanitize($GLOBALS['conn'], $_POST['message'] ?? '');

        if (!$customer_id || !$type || !$message) {
            echo json_encode(['success' => false, 'message' => 'Missing required fields']);
            return;
        }

        $account_id = intval($_SESSION['account_id']);
        $result = $GLOBALS['conn']->query(
            "SELECT * FROM customers WHERE id = $customer_id AND account_id = $account_id"
        );

        if ($result->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Customer not found']);
            return;
        }

        $customer = $result->fetch_assoc();
        $to       = ($type === 'email') ? $customer['email'] : $customer['phone'];

        if (!$to) {
            echo json_encode(['success' => false, 'message' => 'Customer has no ' . ($type === 'email' ? 'email' : 'phone number')]);
            return;
        }

        switch ($type) {
            case 'whatsapp':
                $mediaUrl = handleWhatsAppMediaUpload();
                if (is_array($mediaUrl) && isset($mediaUrl['success']) && !$mediaUrl['success']) { echo json_encode($mediaUrl); return; }
                $res = sendWhatsAppMessage($to, $message, $mediaUrl ?: '');
                break;
            case 'email':    $res = sendEmail($to, $subject, $message); break;
            default:
                echo json_encode(['success' => false, 'message' => 'Unknown type']);
                return;
        }

        logCommunication($customer_id, $type, $to, $subject, $message, $res);
        echo json_encode($res);
    }

    // ------------------------------------------------------------------
    // LOG ONLY — used by SMS after the browser sends it directly
    // ------------------------------------------------------------------
    function logOnly() {
    global $conn;
    $target_type = $_POST['target_type'] ?? '';
    $permPage = ($target_type === 'lead') ? 'leads' : 'customers';
    requirePermission($conn, $permPage, $permPage === 'leads' ? 'take_action' : 'message');
        $type        = $_POST['type']        ?? '';
        $customer_id = intval($_POST['customer_id'] ?? 0);
        $subject     = sanitize($GLOBALS['conn'], $_POST['subject']  ?? '');
        $message     = sanitize($GLOBALS['conn'], $_POST['message']  ?? '');
        $status      = $_POST['status']   === 'sent' ? 'sent' : 'failed';
        $response    = sanitize($GLOBALS['conn'], $_POST['response'] ?? '');

        if (!$customer_id || !$type || !$message) {
            echo json_encode(['success' => false, 'message' => 'Missing required fields']);
            return;
        }

        $account_id = intval($_SESSION['account_id']);
        $result = $GLOBALS['conn']->query(
            "SELECT phone, email FROM customers WHERE id = $customer_id AND account_id = $account_id"
        );

        if ($result->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Customer not found']);
            return;
        }

        $customer = $result->fetch_assoc();
        $to       = ($type === 'email') ? $customer['email'] : $customer['phone'];

        logCommunication($customer_id, $type, $to, $subject, $message, [
            'success' => ($status === 'sent'),
            'message' => $response,
        ]);

        echo json_encode(['success' => true]);
    }


    function handleWhatsAppMediaUpload() {
        if (!isset($_FILES['media']) || empty($_FILES['media']['name'])) {
            return '';
        }

        if ($_FILES['media']['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'message' => 'Image upload failed'];
        }

        $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $ext = strtolower(pathinfo($_FILES['media']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt)) {
            return ['success' => false, 'message' => 'Invalid image type. Allowed: JPG, PNG, GIF, WEBP'];
        }

        if ($_FILES['media']['size'] > 5 * 1024 * 1024) {
            return ['success' => false, 'message' => 'Image is too large. Max 5MB'];
        }

        // Use the same upload folder used by items/products/services:
        // uploads/user_{user_id}/filename.ext
        $uploadDir = getUserUploadPath();
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $userId = intval($_SESSION['user_id'] ?? 0);
        $fileName = 'wa_' . $userId . '_' . time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
        $target = rtrim($uploadDir, '/\\') . DIRECTORY_SEPARATOR . $fileName;

        if (!move_uploaded_file($_FILES['media']['tmp_name'], $target)) {
            return ['success' => false, 'message' => 'Could not save uploaded image'];
        }

        // Return full public link for WhatsApp API mediaUrl
        return getAppBaseUrl() . '/uploads/user_' . $userId . '/' . rawurlencode($fileName);
    }

    function getAppBaseUrl(): string {
        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? '') == 443);
        $scheme = $https ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? '';

        $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
        // handlers => project root
        $rootDir = preg_replace('#/handlers$#', '', $scriptDir);
        $rootDir = rtrim($rootDir, '/');

        return $scheme . '://' . $host . $rootDir;
    }

    // ------------------------------------------------------------------
    // WhatsApp — create campaign → add contact → start campaign
    // ------------------------------------------------------------------
    function sendWhatsAppMessage(string $phone, string $message, string $mediaUrl = ''): array {
         $account_id = intval($_SESSION['account_id']);
        $result = $GLOBALS['conn']->query("
        SELECT client_id, phone_number
        FROM contact_phone
        WHERE account_id = $account_id
        LIMIT 1
        ");
        if (!$result || $result->num_rows == 0) {
        return [
        'success' => false,
        'message' => 'WhatsApp client not found'
        ];
        }
        $contactData = $result->fetch_assoc();
        $clientId   = $contactData['client_id'];
        
        $nodeUrl  = 'https://amctag-whats.38f0fz.easypanel.host';
        $token    = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJmN2M5YTFhMjU1OWRiMWIzYzNhZTQzZWQiLCJ0eXBlIjoidXNlciIsImlhdCI6MTc4MDU3MjY2MX0.4t7g1F4e4k5b0Tu1vjQQu-8Sh2EuT8dR45jR5mimHFs';
        // $clientId = 'a435b397b83218ea8f789299';

        // Normalize phone
        $phone = preg_replace('/[^0-9]/', '', $phone);
        if (substr($phone, 0, 1) === '0')   $phone = substr($phone, 1);
        if (substr($phone, 0, 3) !== '961') $phone = '961' . $phone;

        // 1) Create campaign
        $ch = curl_init($nodeUrl . '/api/campaigns');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode(array_filter([
                'name'      => 'single_' . time(),
                'message'   => $message,
                'clientId'  => $clientId,
                'mediaUrl'  => $mediaUrl ?: null,
                'mediaType' => $mediaUrl ? 'image' : null,
            ], function($value) { return $value !== null && $value !== ''; })),
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: Bearer ' . $token],
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $createResp = curl_exec($ch);
        $httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 && $httpCode !== 201) {
            return ['success' => false, 'message' => 'Campaign create failed', 'response' => $createResp];
        }

        $createData = json_decode($createResp, true);
        $campaignId = $createData['campaign']['_id'] ?? $createData['campaign']['id'] ?? null;

        if (!$campaignId) {
            return ['success' => false, 'message' => 'No campaign ID returned'];
        }

        // 2) Add contact
        $ch = curl_init($nodeUrl . "/api/contacts/{$campaignId}/add");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode(['phone' => $phone, 'name' => 'Customer']),
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: Bearer ' . $token],
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $addResp  = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 && $httpCode !== 201) {
            return ['success' => false, 'message' => 'Contact add failed', 'response' => $addResp];
        }

        // 3) Start campaign
        $ch = curl_init($nodeUrl . "/api/campaigns/{$campaignId}/start");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode([]),
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: Bearer ' . $token],
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $startResp = curl_exec($ch);
        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 && $httpCode !== 201) {
            return ['success' => false, 'message' => 'Campaign start failed', 'response' => $startResp];
        }

        return ['success' => true, 'message' => 'WhatsApp message sent successfully', 'campaignId' => $campaignId];
    }

    // ------------------------------------------------------------------
    // Email
    // ------------------------------------------------------------------
    function sendEmail($to, $subject, $message) {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $account_id = intval($_SESSION['account_id'] ?? 0);
            $fromEmail = 'monzermahfouz54321m@gmail.com';
            if (tableExists($GLOBALS['conn'], 'accounts_email')) {
                $em = $GLOBALS['conn']->query("SELECT email FROM accounts_email WHERE account_id=$account_id ORDER BY is_default DESC, id DESC LIMIT 1");
                if ($em && $em->num_rows) $fromEmail = $em->fetch_assoc()['email'];
            }
            $mail->Username   = 'monzermahfouz54321m@gmail.com';
            $mail->Password   = 'qxsx gwuz eies yiqi';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;

            $mail->setFrom($fromEmail, 'CRM System');
            $mail->addAddress($to);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = nl2br($message);
            $mail->AltBody = strip_tags($message);
            $mail->send();

            return ['success' => true, 'message' => 'Email sent successfully'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $mail->ErrorInfo];
        }
    }

    // ------------------------------------------------------------------
    // Log to DB
    // ------------------------------------------------------------------
    function logCommunication($customer_id, $type, $to, $subject, $message, $result) {
        $status   = $result['success'] ? 'sent' : 'failed';
        $response = $GLOBALS['conn']->real_escape_string($result['message'] ?? '');

        // All type checks lowercase — must match what the form/JS sends
        if ($type === 'sms') {
            $message_type_id = '2';
            $sender          = 'Amctag';
        } elseif ($type === 'email') {
            $message_type_id = '1';
            $sender          = 'Email CRM';
        } elseif ($type === 'whatsapp') {
            $message_type_id = '3';
            $sender          = 'WhatsApp CRM';
        } else {
            $message_type_id = '';
            $sender          = 'Unknown';
        }

        $sender   = $GLOBALS['conn']->real_escape_string($sender);
        $subject  = $GLOBALS['conn']->real_escape_string($subject);
        $message  = $GLOBALS['conn']->real_escape_string($message);
        $to       = $GLOBALS['conn']->real_escape_string($to);

        $account_id = intval($_SESSION['account_id'] ?? 0);
        $user_id = intval($_SESSION['user_id'] ?? 0);
        if (columnExists($GLOBALS['conn'], 'communications', 'account_id')) {
            $GLOBALS['conn']->query(
                "INSERT INTO communications (account_id, user_id, customer_id, message_type_id, recipient, sender, subject, message, status, response, date_created)
                 VALUES ($account_id, $user_id, $customer_id, '$message_type_id', '$to', '$sender', '$subject', '$message', '$status', '$response', NOW())"
            );
        } else {
            $GLOBALS['conn']->query(
                "INSERT INTO communications (customer_id, message_type_id, recipient, sender, subject, message, status, response, date_created)
                 VALUES ($customer_id, '$message_type_id', '$to', '$sender', '$subject', '$message', '$status', '$response', NOW())"
            );
        }
    }

    if (!function_exists('sanitize')) {
        function sanitize($conn, $input) {
            return mysqli_real_escape_string($conn, htmlspecialchars(trim($input)));
        }
    }
?>