<?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(['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'];
        $lead_id  = intval($_POST['lead_id'] ?? 0);
        $include_item_image = intval($_POST['include_item_image'] ?? 0);

        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; }
                if (!$mediaUrl && $include_item_image && $lead_id) $mediaUrl = getLeadItemImageUrl($lead_id);
                $res = sendWhatsAppMessage($to, $message, $mediaUrl ?: '');
                break;
            case 'email':
                $mediaPath = handleEmailMediaUploadPath();
                if (is_array($mediaPath) && isset($mediaPath['success']) && !$mediaPath['success']) { echo json_encode($mediaPath); return; }
                if (!$mediaPath && $include_item_image && $lead_id) $mediaPath = getLeadItemImagePath($lead_id);
                $res = sendEmail($to, $subject, $message, $mediaPath ?: '');
                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'];
        $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(['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  = 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    = nl2br(htmlspecialchars($message));
            $mail->AltBody = strip_tags($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   = $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')) {
            $source_type = $GLOBALS['conn']->real_escape_string($_POST['target_type'] ?? 'direct');
            if (columnExists($GLOBALS['conn'],'communications','source_type')) {
                $GLOBALS['conn']->query("INSERT INTO communications (account_id, user_id, customer_id, campaign_id, source_type, message_type_id, recipient, sender, subject, message, status, response, date_created) VALUES ($account_id, $user_id, $customer_id, NULL, '$source_type', '$message_type_id', '$to', '$sender', '$subject', '$message', '$status', '$response', NOW())");
            } else {
            $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)));
        }
    }
?>