<?php
// MJ Marketplace v2.9.16 - Deals display/enquiry helper.
// Business rule: customers never pay sellers/users through MJ Marketplace.

if (!function_exists('mj_deal_ensure_schema')) {
function mj_deal_ensure_schema(): void {
    if (!function_exists('q') || !mj_is_installed()) { return; }
    try {
        q("CREATE TABLE IF NOT EXISTS mj_deals (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            user_id BIGINT NULL,
            company_id BIGINT NULL,
            category_id INT NULL,
            country_id INT NULL,
            city_id BIGINT NULL,
            deal_type VARCHAR(60) NOT NULL DEFAULT 'normal',
            title VARCHAR(255) NOT NULL,
            slug VARCHAR(255) NULL,
            short_description VARCHAR(500) NULL,
            description MEDIUMTEXT NULL,
            image_path VARCHAR(500) NULL,
            original_price DECIMAL(12,2) DEFAULT 0,
            deal_price DECIMAL(12,2) DEFAULT 0,
            discount_percent DECIMAL(8,2) DEFAULT 0,
            price_note VARCHAR(255) NULL,
            currency_code VARCHAR(8) DEFAULT 'SGD',
            start_at DATETIME NULL,
            end_at DATETIME NULL,
            status VARCHAR(40) NOT NULL DEFAULT 'pending',
            is_featured TINYINT(1) NOT NULL DEFAULT 0,
            is_sponsored TINYINT(1) NOT NULL DEFAULT 0,
            featured_until DATETIME NULL,
            sponsored_until DATETIME NULL,
            contact_phone VARCHAR(80) NULL,
            contact_whatsapp VARCHAR(80) NULL,
            contact_email VARCHAR(190) NULL,
            terms TEXT NULL,
            quality_score INT NOT NULL DEFAULT 0,
            view_count INT NOT NULL DEFAULT 0,
            enquiry_count INT NOT NULL DEFAULT 0,
            whatsapp_click_count INT NOT NULL DEFAULT 0,
            call_click_count INT NOT NULL DEFAULT 0,
            email_click_count INT NOT NULL DEFAULT 0,
            share_count INT NOT NULL DEFAULT 0,
            qr_scan_count INT NOT NULL DEFAULT 0,
            reject_reason TEXT NULL,
            admin_note TEXT NULL,
            approved_by INT NULL,
            approved_at DATETIME NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_user_status(user_id,status),
            INDEX idx_country_status(country_id,status),
            INDEX idx_category_status(category_id,status),
            INDEX idx_end_at(end_at),
            INDEX idx_featured(is_featured,is_sponsored)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    } catch (Throwable $e) {}
    try {
        q("CREATE TABLE IF NOT EXISTS mj_deal_enquiries (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            deal_id BIGINT NOT NULL,
            seller_user_id BIGINT NULL,
            company_id BIGINT NULL,
            customer_user_id BIGINT NULL,
            name VARCHAR(160) NOT NULL,
            email VARCHAR(190) NULL,
            phone VARCHAR(80) NULL,
            preferred_datetime VARCHAR(120) NULL,
            message TEXT NULL,
            status VARCHAR(40) NOT NULL DEFAULT 'new',
            source VARCHAR(60) NOT NULL DEFAULT 'deal_page',
            admin_note TEXT NULL,
            ip_address VARCHAR(80) NULL,
            user_agent TEXT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NULL,
            INDEX idx_deal_status(deal_id,status),
            INDEX idx_seller_status(seller_user_id,status),
            INDEX idx_company(company_id),
            INDEX idx_created(created_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    } catch (Throwable $e) {}
    // Backward-compatible columns for older installations where mj_deals existed as a placeholder/voucher table.
    try {
        $cols = [
            'user_id' => 'ALTER TABLE mj_deals ADD COLUMN user_id BIGINT NULL AFTER id',
            'deal_type' => 'ALTER TABLE mj_deals ADD COLUMN deal_type VARCHAR(60) NOT NULL DEFAULT \'normal\' AFTER city_id',
            'short_description' => 'ALTER TABLE mj_deals ADD COLUMN short_description VARCHAR(500) NULL AFTER slug',
            'price_note' => 'ALTER TABLE mj_deals ADD COLUMN price_note VARCHAR(255) NULL AFTER discount_percent',
            'featured_until' => 'ALTER TABLE mj_deals ADD COLUMN featured_until DATETIME NULL AFTER is_featured',
            'contact_phone' => 'ALTER TABLE mj_deals ADD COLUMN contact_phone VARCHAR(80) NULL AFTER sponsored_until',
            'contact_whatsapp' => 'ALTER TABLE mj_deals ADD COLUMN contact_whatsapp VARCHAR(80) NULL AFTER contact_phone',
            'contact_email' => 'ALTER TABLE mj_deals ADD COLUMN contact_email VARCHAR(190) NULL AFTER contact_whatsapp',
            'quality_score' => 'ALTER TABLE mj_deals ADD COLUMN quality_score INT NOT NULL DEFAULT 0 AFTER terms',
            'view_count' => 'ALTER TABLE mj_deals ADD COLUMN view_count INT NOT NULL DEFAULT 0 AFTER quality_score',
            'enquiry_count' => 'ALTER TABLE mj_deals ADD COLUMN enquiry_count INT NOT NULL DEFAULT 0 AFTER view_count',
            'whatsapp_click_count' => 'ALTER TABLE mj_deals ADD COLUMN whatsapp_click_count INT NOT NULL DEFAULT 0 AFTER enquiry_count',
            'call_click_count' => 'ALTER TABLE mj_deals ADD COLUMN call_click_count INT NOT NULL DEFAULT 0 AFTER whatsapp_click_count',
            'email_click_count' => 'ALTER TABLE mj_deals ADD COLUMN email_click_count INT NOT NULL DEFAULT 0 AFTER call_click_count',
            'share_count' => 'ALTER TABLE mj_deals ADD COLUMN share_count INT NOT NULL DEFAULT 0 AFTER email_click_count',
            'qr_scan_count' => 'ALTER TABLE mj_deals ADD COLUMN qr_scan_count INT NOT NULL DEFAULT 0 AFTER share_count',
            'reject_reason' => 'ALTER TABLE mj_deals ADD COLUMN reject_reason TEXT NULL AFTER qr_scan_count',
            'admin_note' => 'ALTER TABLE mj_deals ADD COLUMN admin_note TEXT NULL AFTER reject_reason',
            'approved_by' => 'ALTER TABLE mj_deals ADD COLUMN approved_by INT NULL AFTER admin_note',
            'approved_at' => 'ALTER TABLE mj_deals ADD COLUMN approved_at DATETIME NULL AFTER approved_by'
        ];
        foreach ($cols as $col => $sql) { if (!mj_column_exists('mj_deals', $col)) { try { q($sql); } catch(Throwable $ignore) {} } }
        try { q('ALTER TABLE mj_deals MODIFY status VARCHAR(40) NOT NULL DEFAULT \'pending\''); } catch(Throwable $ignore) {}
    } catch (Throwable $e) {}

    try {
        q("CREATE TABLE IF NOT EXISTS mj_deal_events (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            deal_id BIGINT NOT NULL,
            user_id BIGINT NULL,
            event_type VARCHAR(80) NOT NULL,
            event_value VARCHAR(255) NULL,
            ip_address VARCHAR(80) NULL,
            user_agent TEXT NULL,
            session_key VARCHAR(191) NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_deal_type(deal_id,event_type),
            INDEX idx_created(created_at),
            INDEX idx_session(session_key)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    } catch (Throwable $e) {}
}
}


if (!function_exists('mj_deal_filter_existing_columns')) {
function mj_deal_filter_existing_columns(array $data): array {
    $cols = [];
    try {
        $rows = all_rows("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'mj_deals'");
        foreach ($rows as $r) { $cols[strtolower((string)$r['COLUMN_NAME'])] = true; }
    } catch (Throwable $e) {}
    if (!$cols) { return $data; }
    $out = [];
    foreach ($data as $k=>$v) { if (isset($cols[strtolower((string)$k)])) { $out[$k]=$v; } }
    return $out;
}
}

if (!function_exists('mj_deal_column_defaults')) {
function mj_deal_column_defaults(): array {
    return [
        'user_id'=>null,'company_id'=>null,'category_id'=>null,'country_id'=>null,'city_id'=>null,'deal_type'=>'normal','title'=>'','slug'=>'','short_description'=>'','description'=>'','image_path'=>'','original_price'=>0,'deal_price'=>0,'discount_percent'=>0,'price_note'=>'','currency_code'=>'SGD','start_at'=>null,'end_at'=>null,'status'=>'pending','is_featured'=>0,'is_sponsored'=>0,'featured_until'=>null,'sponsored_until'=>null,'contact_phone'=>'','contact_whatsapp'=>'','contact_email'=>'','terms'=>'','quality_score'=>0,'reject_reason'=>'','admin_note'=>''
    ];
}
}

if (!function_exists('mj_deal_quality_score')) {
function mj_deal_quality_score(array $d): int {
    $score = 0;
    if (mb_strlen(trim((string)($d['title'] ?? ''))) >= 10) $score += 20;
    if (trim((string)($d['image_path'] ?? '')) !== '') $score += 20;
    if (mb_strlen(trim(strip_tags((string)($d['description'] ?? '')))) >= 80) $score += 20;
    if ((float)($d['deal_price'] ?? 0) > 0 || trim((string)($d['price_note'] ?? '')) !== '') $score += 15;
    if ((int)($d['country_id'] ?? 0) > 0) $score += 10;
    if (trim((string)($d['terms'] ?? '')) !== '') $score += 10;
    if (trim((string)($d['contact_whatsapp'] ?? '')) !== '' || trim((string)($d['contact_phone'] ?? '')) !== '' || filter_var((string)($d['contact_email'] ?? ''), FILTER_VALIDATE_EMAIL)) $score += 5;
    return min(100, $score);
}
}

if (!function_exists('mj_deal_discount_percent')) {
function mj_deal_discount_percent($original, $deal): float {
    $original = (float)$original; $deal = (float)$deal;
    if ($original <= 0 || $deal <= 0 || $deal >= $original) { return 0.0; }
    return round((($original - $deal) / $original) * 100, 2);
}
}

if (!function_exists('mj_deal_public_url')) {
function mj_deal_public_url(array $d): string {
    $id = (int)($d['id'] ?? 0);
    $slug = trim((string)($d['slug'] ?? ''));
    return base_url('deal.php?id='.$id.($slug !== '' ? '&slug='.rawurlencode($slug) : ''));
}
}

if (!function_exists('mj_deal_status_badge')) {
function mj_deal_status_badge(string $status): string {
    $s = strtolower(trim($status));
    $map = ['active'=>'success','approved'=>'success','pending'=>'warning','draft'=>'secondary','expired'=>'dark','rejected'=>'danger','paused'=>'info','hidden'=>'secondary'];
    $class = $map[$s] ?? 'secondary';
    return '<span class="badge badge-'.$class.'">'.e(ucwords(str_replace('_',' ',$s ?: 'draft'))).'</span>';
}
}

if (!function_exists('mj_deal_public_where')) {
function mj_deal_public_where(string $alias='d'): string {
    $a = preg_replace('/[^a-zA-Z0-9_]/','',$alias) ?: 'd';
    return $a.".status IN ('active','approved') AND (".$a.".start_at IS NULL OR ".$a.".start_at<=NOW()) AND (".$a.".end_at IS NULL OR ".$a.".end_at>=NOW())";
}
}

if (!function_exists('mj_deal_fetch')) {
function mj_deal_fetch(int $id, bool $publicOnly=true): ?array {
    mj_deal_ensure_schema();
    try {
        $sql = "SELECT d.*, co.name AS company_name, co.slug AS company_slug, co.phone AS company_phone, co.whatsapp AS company_whatsapp, co.email AS company_email, co.address AS company_address, u.name AS user_name, u.email AS user_email, u.mobile AS user_mobile, c.name AS country_name, ci.name AS city_name, cat.name AS category_name
                FROM mj_deals d
                LEFT JOIN mj_companies co ON co.id=d.company_id
                LEFT JOIN mj_users u ON u.id=d.user_id
                LEFT JOIN mj_countries c ON c.id=d.country_id
                LEFT JOIN mj_cities ci ON ci.id=d.city_id
                LEFT JOIN mj_categories cat ON cat.id=d.category_id
                WHERE d.id=?";
        if ($publicOnly) { $sql .= ' AND '.mj_deal_public_where('d'); }
        $sql .= ' LIMIT 1';
        return one($sql, [$id]);
    } catch (Throwable $e) { return null; }
}
}

if (!function_exists('mj_deal_contact')) {
function mj_deal_contact(array $d): array {
    $phone = trim((string)($d['contact_phone'] ?? '')) ?: trim((string)($d['company_phone'] ?? '')) ?: trim((string)($d['user_mobile'] ?? ''));
    $wa = trim((string)($d['contact_whatsapp'] ?? '')) ?: trim((string)($d['company_whatsapp'] ?? '')) ?: $phone;
    $email = trim((string)($d['contact_email'] ?? '')) ?: trim((string)($d['company_email'] ?? '')) ?: trim((string)($d['user_email'] ?? ''));
    $waDigits = preg_replace('/[^0-9]/','',$wa);
    return ['phone'=>$phone,'whatsapp'=>$wa,'whatsapp_digits'=>$waDigits,'email'=>$email];
}
}

if (!function_exists('mj_deal_track_event')) {
function mj_deal_track_event(int $dealId, string $type, string $value=''): void {
    mj_deal_ensure_schema();
    try {
        $session = session_id() ?: ($_COOKIE[session_name()] ?? 'guest');
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
        if ($type === 'view') {
            $exists = one('SELECT id FROM mj_deal_events WHERE deal_id=? AND event_type="view" AND (session_key=? OR ip_address=?) AND created_at >= DATE_SUB(NOW(), INTERVAL 6 HOUR) LIMIT 1', [$dealId,$session,$ip]);
            if ($exists) { return; }
        }
        q('INSERT INTO mj_deal_events(deal_id,user_id,event_type,event_value,ip_address,user_agent,session_key,created_at) VALUES(?,?,?,?,?,?,?,NOW())', [$dealId,$_SESSION['user_id']??null,$type,$value,$ip,$_SERVER['HTTP_USER_AGENT']??'',$session]);
        $map = ['view'=>'view_count','enquiry'=>'enquiry_count','whatsapp'=>'whatsapp_click_count','call'=>'call_click_count','email'=>'email_click_count','share'=>'share_count','qr'=>'qr_scan_count'];
        if (isset($map[$type]) && mj_column_exists('mj_deals',$map[$type])) {
            q('UPDATE mj_deals SET `'.$map[$type].'`=`'.$map[$type].'`+1 WHERE id=?', [$dealId]);
        }
    } catch (Throwable $e) {}
}
}

if (!function_exists('mj_deal_submit_enquiry')) {
function mj_deal_submit_enquiry(array $deal, array $data): array {
    mj_deal_ensure_schema();
    $name = trim((string)($data['name'] ?? ''));
    $email = trim((string)($data['email'] ?? ''));
    $phone = trim((string)($data['phone'] ?? ''));
    $message = trim((string)($data['message'] ?? ''));
    $preferred = trim((string)($data['preferred_datetime'] ?? ''));
    if ($name === '') { return ['success'=>false,'error'=>'Please enter your name.']; }
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) { return ['success'=>false,'error'=>'Please enter a valid email address.']; }
    if ($phone === '' && $email === '') { return ['success'=>false,'error'=>'Please enter phone or email so seller can contact you.']; }
    if ($message === '') { $message = 'I am interested in this deal. Please contact me.'; }
    try {
        q('INSERT INTO mj_deal_enquiries(deal_id,seller_user_id,company_id,customer_user_id,name,email,phone,preferred_datetime,message,status,ip_address,user_agent,created_at) VALUES(?,?,?,?,?,?,?,?,?,"new",?,?,NOW())', [
            (int)$deal['id'], (int)($deal['user_id'] ?? 0) ?: null, (int)($deal['company_id'] ?? 0) ?: null, $_SESSION['user_id'] ?? null, $name, $email ?: null, $phone ?: null, $preferred ?: null, $message, $_SERVER['REMOTE_ADDR'] ?? '', $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        $enquiryId = (int)db()->lastInsertId();
        mj_deal_track_event((int)$deal['id'], 'enquiry');
        $leadId = 0;
        try { if (function_exists('mj_leads_record_deal_enquiry')) { $leadId = mj_leads_record_deal_enquiry($deal, $enquiryId, ['name'=>$name,'email'=>$email,'phone'=>$phone,'message'=>$message,'preferred_datetime'=>$preferred]); } } catch(Throwable $ignore) {}
        try { if (function_exists('mjv3041_record_seller_lead')) { mjv3041_record_seller_lead(['seller_user_id'=>(int)($deal['user_id'] ?? 0),'source_type'=>'deal','source_id'=>(int)$deal['id'],'source_title'=>(string)($deal['title'] ?? 'Deal'),'customer_name'=>$name,'customer_email'=>$email,'customer_phone'=>$phone,'customer_message'=>$message]); } } catch(Throwable $ignore) {}
        $leadUrl = 'my-leads.php?source=deal'.($leadId ? '&lead='.$leadId : '');
        try { mj263_notify((int)($deal['user_id'] ?? 0) ?: null, null, 'deal_enquiry', 'New deal enquiry', 'A customer enquired about: '.($deal['title'] ?? 'Deal'), $leadUrl, 'high', true); } catch(Throwable $ignore) {}
        try { if (function_exists('mj_leads_notify_admins')) { mj_leads_notify_admins('New deal enquiry', 'A customer enquired about: '.($deal['title'] ?? 'Deal'), 'leads.php?source=deal'); } } catch(Throwable $ignore) {}
        try {
            require_once __DIR__ . '/mj_email_helpers.php';
            $contact = mj_deal_contact($deal);
            $sellerEmail = $contact['email'];
            $adminEmail = setting('admin_email','');
            $subject = 'New deal enquiry: '.(string)($deal['title'] ?? 'Deal');
            $html = '<h2>New deal enquiry</h2><p><b>Deal:</b> '.e((string)($deal['title'] ?? '')).'</p><p><b>Name:</b> '.e($name).'<br><b>Email:</b> '.e($email).'<br><b>Phone:</b> '.e($phone).'</p><p><b>Preferred:</b> '.e($preferred).'</p><p>'.nl2br(e($message)).'</p><p><a href="'.e(mj_deal_public_url($deal)).'">View Deal</a></p><p style="color:#666">MJ Marketplace does not collect customer payment for deals. Seller must contact customer directly.</p>';
            $text = strip_tags(str_replace(['<br>','<br/>','<br />'], "\n", $html));
            if ($sellerEmail && filter_var($sellerEmail, FILTER_VALIDATE_EMAIL)) { mj_send_email($sellerEmail, $subject, $html, $text, ['template_key'=>'deal_enquiry']); }
            if ($adminEmail && filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) { mj_send_email($adminEmail, '[Admin] '.$subject, $html, $text, ['template_key'=>'deal_enquiry_admin']); }
        } catch(Throwable $ignore) {}
        return ['success'=>true,'id'=>$enquiryId];
    } catch (Throwable $e) { return ['success'=>false,'error'=>'Unable to send enquiry now. Please try again later.']; }
}
}

if (!function_exists('mj_deal_admin_summary')) {
function mj_deal_admin_summary(): array {
    mj_deal_ensure_schema();
    return [
        'total'=>safe_count('SELECT COUNT(*) c FROM mj_deals'),
        'pending'=>safe_count('SELECT COUNT(*) c FROM mj_deals WHERE status="pending"'),
        'active'=>safe_count('SELECT COUNT(*) c FROM mj_deals WHERE status IN ("active","approved")'),
        'expired'=>safe_count('SELECT COUNT(*) c FROM mj_deals WHERE status="expired" OR (end_at IS NOT NULL AND end_at<NOW())'),
        'enquiries'=>safe_count('SELECT COUNT(*) c FROM mj_deal_enquiries'),
        'new_enquiries'=>safe_count('SELECT COUNT(*) c FROM mj_deal_enquiries WHERE status="new"')
    ];
}
}
