<?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));
    crmDecodeIdsInArray($_POST);

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

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

    // ------------------------------------------------------------------
    // 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     = trim((string)($_POST['subject'] ?? ''));
        $rawMessage  = trim((string)($_POST['message'] ?? ''));
        $message     = crmPlainMessage($rawMessage);

        if (!$customer_id || !$type || !$message) {
            echo json_encode(crmJson(['success' => false, 'message' => 'Missing required fields']), JSON_UNESCAPED_UNICODE);
            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(crmJson(['success' => false, 'message' => 'Customer not found']), JSON_UNESCAPED_UNICODE);
            return;
        }

        $customer = $result->fetch_assoc();
        $to       = ($type === 'email') ? $customer['email'] : $customer['phone'];
        $lead_id  = intval($_POST['lead_id'] ?? 0);
        $include_item_image = intval($_POST['include_item_image'] ?? 0);

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

        switch ($type) {
            case 'whatsapp':
                $mediaUrl = handleWhatsAppMediaUpload();
                if (is_array($mediaUrl) && isset($mediaUrl['success']) && !$mediaUrl['success']) { echo json_encode(crmJson($mediaUrl), JSON_UNESCAPED_UNICODE); return; }
                if (!$mediaUrl && $include_item_image && $lead_id) $mediaUrl = getLeadItemImageUrl($lead_id);
                $res = sendWhatsAppMessage($to, crmPlainMessage($rawMessage), $mediaUrl ?: '');
                break;
            case 'email':
                $mediaPath = handleEmailMediaUploadPath();
                if (is_array($mediaPath) && isset($mediaPath['success']) && !$mediaPath['success']) { echo json_encode(crmJson($mediaPath), JSON_UNESCAPED_UNICODE); return; }
                if (!$mediaPath && $include_item_image && $lead_id) $mediaPath = getLeadItemImagePath($lead_id);
                $res = sendEmail($to, $subject, crmEmailBody($rawMessage), $mediaPath ?: '');
                break;
            default:
                echo json_encode(crmJson(['success' => false, 'message' => 'Unknown type']), JSON_UNESCAPED_UNICODE);
                return;
        }

        $logMsg = ($type === 'email') ? crmEmailBody($rawMessage) : crmPlainMessage($rawMessage);
        logCommunication($customer_id, $type, $to, $subject, $logMsg, $res);
        echo json_encode(crmJson($res), JSON_UNESCAPED_UNICODE);
    }

    // ------------------------------------------------------------------
    // 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     = trim((string)($_POST['subject']  ?? ''));
        $message     = crmPlainMessage((string)($_POST['message']  ?? ''));
        $status      = $_POST['status']   === 'sent' ? 'sent' : 'failed';
        $response    = sanitize($GLOBALS['conn'], $_POST['response'] ?? '');

        if (!$customer_id || !$type || !$message) {
            echo json_encode(crmJson(['success' => false, 'message' => 'Missing required fields']), JSON_UNESCAPED_UNICODE);
            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(crmJson(['success' => false, 'message' => 'Customer not found']), JSON_UNESCAPED_UNICODE);
            return;
        }

        $customer = $result->fetch_assoc();
        $to       = ($type === 'email') ? $customer['email'] : $customer['phone'];
        $lead_id  = intval($_POST['lead_id'] ?? 0);
        $include_item_image = intval($_POST['include_item_image'] ?? 0);

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

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



    function crmPlainMessage(string $message): string {
        $message = html_entity_decode($message, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $message = str_replace(["\\r\\n", "\\n", "\\r"], ["\n", "\n", "\n"], $message);
        $message = preg_replace('/<\s*br\s*\/?>/i', "\n", $message);
        $message = preg_replace('/<\s*\/\s*(p|div|li|h[1-6])\s*>/i', "\n", $message);
        $message = strip_tags($message);
        $message = preg_replace("/\n{3,}/", "\n\n", $message);
        return trim($message);
    }

    function crmEmailBody(string $message): string {
        $message = html_entity_decode($message, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $message = str_replace(["\\r\\n", "\\n", "\\r"], ["\n", "\n", "\n"], $message);
        if (preg_match('/<\s*(br|p|div|b|strong|i|em|u|ul|ol|li|span)\b/i', $message)) {
            $allowed = '<br><p><div><b><strong><i><em><u><ul><ol><li><span>';
            return trim(strip_tags($message, $allowed));
        }
        return nl2br(htmlspecialchars(trim($message), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'));
    }

    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  = CRM_WHATSAPP_NODE_URL;
        $token    = CRM_WHATSAPP_TOKEN;
        // $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 handleEmailMediaUploadPath() {
        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'];
        if ($_FILES['media']['size'] > 5*1024*1024) return ['success'=>false,'message'=>'Image too large. Max 5MB'];
        $dir = getUserUploadPath(); $file = 'contact_'.intval($_SESSION['user_id']).'_'.time().'_'.rand(1000,9999).'.'.$ext;
        $path = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR . $file; if (!move_uploaded_file($_FILES['media']['tmp_name'],$path)) return ['success'=>false,'message'=>'Could not save image'];
        return $path;
    }
    function getLeadItemImagePath($lead_id) {
        $account_id = intval($_SESSION['account_id'] ?? 0);
        $q=$GLOBALS['conn']->query("SELECT ii.image_path, i.image, l.created_by_user_id, l.assigned_user_id FROM leads l LEFT JOIN items i ON i.id=l.item_id LEFT JOIN item_images ii ON ii.item_id=l.item_id WHERE l.id=$lead_id AND l.account_id=$account_id ORDER BY ii.is_primary DESC, ii.sort_order ASC, ii.id ASC LIMIT 1");
        if(!$q || !$q->num_rows) return '';
        $r=$q->fetch_assoc();
        $img = $r['image_path'] ?: ($r['image'] ?? '');
        if(!$img) return '';
        if(strpos($img, '/') === 0 && file_exists($img)) return $img;
        $root = dirname(__DIR__);
        $candidates = [];
        foreach ([intval($r['created_by_user_id']), intval($r['assigned_user_id']), intval($_SESSION['user_id'] ?? 0)] as $uid) {
            if($uid) $candidates[] = $root.'/uploads/user_'.$uid.'/'.$img;
        }
        $candidates[] = $root.'/uploads/'.$img;
        $candidates[] = $root.'/'.$img;
        foreach($candidates as $path){ if($path && file_exists($path)) return $path; }
        return '';
    }
    function getLeadItemImageUrl($lead_id) {
        $path = getLeadItemImagePath($lead_id); if(!$path) return '';
        $base = rtrim((defined('APP_URL') ? APP_URL : ''), '/');
        $rel = str_replace(dirname(__DIR__).'/', '', $path);
        return $base ? $base.'/'.$rel : $rel;
    }

    function sendEmail($to, $subject, $message, $attachmentPath='') {
        $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    = $message;
            $mail->AltBody = crmPlainMessage($message);
            if ($attachmentPath && file_exists($attachmentPath)) {
                $cid = 'lead_item_image_' . md5($attachmentPath);
                $mail->addEmbeddedImage($attachmentPath, $cid);
                $mail->Body .= '<br><br><img src="cid:' . $cid . '" style="max-width:520px;width:100%;height:auto;border-radius:10px">';
                $mail->addAttachment($attachmentPath);
            }
            $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   = !empty($result['success']) ? 'sent' : 'failed';
        $response = $GLOBALS['conn']->real_escape_string($result['message'] ?? '');

        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'; }

        $account_id = intval($_SESSION['account_id'] ?? 0);
        $user_id    = intval($_SESSION['user_id'] ?? 0);
        $lead_id    = intval($_POST['lead_id'] ?? 0);
        $source_type_raw = $_POST['target_type'] ?? ($lead_id ? 'lead' : 'direct');
        $source_type = $GLOBALS['conn']->real_escape_string($source_type_raw);
        $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);

        $cols = [];
        $vals = [];
        if (columnExists($GLOBALS['conn'], 'communications', 'account_id')) { $cols[]='account_id'; $vals[]=$account_id; }
        if (columnExists($GLOBALS['conn'], 'communications', 'user_id')) { $cols[]='user_id'; $vals[]=$user_id; }
        $cols[]='customer_id'; $vals[]=$customer_id;
        if ($lead_id && columnExists($GLOBALS['conn'], 'communications', 'lead_id')) { $cols[]='lead_id'; $vals[]=$lead_id; }
        if (columnExists($GLOBALS['conn'], 'communications', 'campaign_id')) { $cols[]='campaign_id'; $vals[]='NULL'; }
        if (columnExists($GLOBALS['conn'], 'communications', 'source_type')) { $cols[]='source_type'; $vals[]="'$source_type'"; }
        $cols[]='message_type_id'; $vals[]="'$message_type_id'";
        $cols[]='recipient'; $vals[]="'$to'";
        $cols[]='sender'; $vals[]="'$sender'";
        $cols[]='subject'; $vals[]="'$subject'";
        $cols[]='message'; $vals[]="'$message'";
        $cols[]='status'; $vals[]="'$status'";
        $cols[]='response'; $vals[]="'$response'";
        $cols[]='date_created'; $vals[]='NOW()';

        $GLOBALS['conn']->query('INSERT INTO communications (`'.implode('`,`',$cols).'`) VALUES ('.implode(',', $vals).')');
    }

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