<?php
require_once __DIR__.'/includes/functions.php';
mj_company_module_ensure_schema();
mj_leads_ensure_schema();
$id = (int)($_GET['id'] ?? 0);
$co = safe_one_public('SELECT co.*, c.name country_name,c.flag_emoji,c.currency_code,ci.name city,cat.name category,u.name owner_name FROM mj_companies co LEFT JOIN mj_countries c ON c.id=co.country_id LEFT JOIN mj_cities ci ON ci.id=co.city_id LEFT JOIN mj_categories cat ON cat.id=co.category_id LEFT JOIN mj_users u ON u.id=co.user_id WHERE co.id=? LIMIT 1', [$id]);
if (!$co) {
    http_response_code(404);
    $pageTitle = 'Company not found';
include __DIR__.'/includes/header.php';
    echo '<section class="mj-section"><div class="container"><div class="alert alert-warning rounded-4">Company not found.</div><a class="btn btn-primary" href="'.e(base_url('companies.php')).'">Browse Companies</a></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}
$user = current_user();
$admin = current_admin();
$isOwner = $user && (int)$user['id'] === (int)$co['user_id'];
$isAdmin = (bool)$admin;
$canViewFullContact = (bool)($user || $admin);
if (!in_array((string)$co['status'], ['active','approved','published'], true) && !$isOwner && !$isAdmin) {
    http_response_code(404);
    $pageTitle = 'Company unavailable';
    include __DIR__.'/includes/header.php';
    echo '<section class="mj-section"><div class="container"><div class="mj-card p-5 text-center"><h1>This company profile is not available yet</h1><p class="text-muted">The company profile may be under review or temporarily unavailable.</p><a class="btn btn-primary" href="'.e(base_url('companies.php')).'">Browse Active Companies</a></div></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}
try { q('UPDATE mj_companies SET views=views+1 WHERE id=?', [$id]); } catch(Throwable $e) { mj_frontend_runtime_error($e, 'update company views'); }
$branches = safe_all_rows_public('SELECT * FROM mj_company_branches WHERE company_id=? AND is_active=1 ORDER BY is_main DESC,id', [$id]);
$services = safe_all_rows_public('SELECT * FROM mj_company_services WHERE company_id=? ORDER BY id DESC LIMIT 20', [$id]);
$listings = safe_all_rows_public('SELECT l.*, c.name country, ci.name city, (SELECT image_path FROM mj_listing_images WHERE listing_id=l.id ORDER BY sort_order,id LIMIT 1) image_path FROM mj_listings l LEFT JOIN mj_countries c ON c.id=l.country_id LEFT JOIN mj_cities ci ON ci.id=l.city_id WHERE l.company_id=? AND '.mj_public_listing_status_sql('l').' ORDER BY l.id DESC LIMIT 8', [$id]);
$serviceCount = count($services);
$profileScore = (int)($co['profile_score'] ?? mj_company_profile_score($co, $serviceCount));
$trustScore = (int)($co['trust_score'] ?? mj_company_trust_score($co, $serviceCount));
$phoneValue = trim((string)($co['phone'] ?? ''));
$mobileValue = trim((string)($co['mobile'] ?? ''));
$whatsappValue = trim((string)($co['whatsapp'] ?? ''));
$mobileOrWhatsapp = $mobileValue !== '' ? $mobileValue : $whatsappValue;
$emailValue = trim((string)($co['email'] ?? ''));
$waNumber = preg_replace('/\D+/', '', (string)($whatsappValue ?: $phoneValue));
$waMsg = rawurlencode('Hi, I found your company "'.$co['name'].'" on MJ Marketplace. I would like to know more about your services.');
$shareUrl = mj_company_public_url($co);
$loginUrl = base_url('login.php?redirect='.rawurlencode('company.php?id='.(int)$co['id']));

verify_csrf();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'company_enquiry') {
    try {
        $leadId = mj_leads_record_company_enquiry($co, $_POST);
        try { q('UPDATE mj_companies SET engagement_count=COALESCE(engagement_count,0)+1 WHERE id=?', [(int)$co['id']]); } catch(Throwable $ignore) {}
        flash('success', 'Your enquiry was sent. The company will contact you directly.');
        redirect('company.php?id='.(int)$id.'#company-enquiry');
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
}

$pageTitle = $co['name'];
$metaDescription = mb_substr(strip_tags((string)($co['description'] ?: $co['address'])), 0, 155);
$companyPageSettings = mj_v288_company_page_settings((int)($co['id'] ?? 0));
$companySections = mj_v288_company_sections((int)($co['id'] ?? 0));
$bookingSettings = mj_v288_booking_settings((int)($co['id'] ?? 0));
$companyThemePrimary = $companyPageSettings['theme_primary'] ?: '#2563eb';
$companyThemeAccent = $companyPageSettings['theme_accent'] ?: '#7c3aed';
$companyCover = $companyPageSettings['cover_image'] ?: ($co['cover_image'] ?? '');
if (!empty($companyPageSettings['seo_title'])) { $pageTitle = $companyPageSettings['seo_title']; }
if (!empty($companyPageSettings['seo_description'])) { $metaDescription = mb_substr(strip_tags((string)$companyPageSettings['seo_description']), 0, 155); }
include __DIR__.'/includes/header.php';
?>
<div class="company-theme-vars" style="--company-primary:<?=e($companyThemePrimary)?>;--company-accent:<?=e($companyThemeAccent)?>"></div>
<section class="mj-hero" style="padding:0;background:#0f172a;">
  <?php if(!empty($companyCover)): ?><div style="height:230px;background:url('<?=e(base_url($companyCover))?>') center/cover no-repeat;opacity:.55"></div><?php endif; ?>
  <div class="container" style="padding:<?=!empty($companyCover)?'0 12px 52px':'58px 12px'?>;margin-top:<?=!empty($companyCover)?'-90px':'0'?>;position:relative">
    <div class="row align-items-end g-4">
      <div class="col-lg-8">
        <div class="d-flex flex-wrap gap-2 mb-3">
          <span class="badge text-bg-light text-primary rounded-pill"><?=e(($co['flag_emoji'] ?? '').' '.($co['country_name'] ?? ''))?> <?=!empty($co['city'])?'• '.e($co['city']):''?></span>
          <?php if(!empty($co['category'])): ?><span class="badge text-bg-light rounded-pill"><?=e($co['category'])?></span><?php endif; ?>
          <?php if((int)($co['is_verified'] ?? 0)): ?><span class="badge text-bg-success rounded-pill"><i class="bi bi-patch-check-fill me-1"></i>Verified Company</span><?php endif; ?>
          <?php if(!empty($co['is_featured'])): ?><span class="badge text-bg-warning rounded-pill">Featured</span><?php endif; ?>
          <?php if(!empty($co['is_sponsored'])): ?><span class="badge text-bg-info rounded-pill">Sponsored</span><?php endif; ?>
        </div>
        <h1 class="display-5 fw-bold mb-3"><?=e($co['name'])?></h1>
        <p class="lead mb-4"><?=e(mb_substr((string)($co['description'] ?: 'View company services, contact details, listings and business information.'), 0, 220))?></p>
        <div class="d-flex flex-wrap gap-2">
          <a class="btn btn-light btn-lg" href="<?=base_url('chat.php?company_id='.(int)$co['id'].'&seller_id='.(int)$co['user_id'])?>"><i class="bi bi-chat-dots me-1"></i>Message Company</a>
          <?php if($waNumber): ?><a class="btn btn-success btn-lg" href="<?=e($canViewFullContact ? ('https://wa.me/'.$waNumber.'?text='.$waMsg) : $loginUrl)?>" <?= $canViewFullContact ? 'target="_blank"' : '' ?>><i class="bi bi-whatsapp me-1"></i><?= $canViewFullContact ? 'WhatsApp' : 'Login for WhatsApp' ?></a><?php endif; ?>
          <?php if(!empty($co['phone'])): ?><a class="btn btn-outline-light btn-lg" href="<?=e($canViewFullContact ? mj_company_contact_href($co['phone'], 'phone') : $loginUrl)?>"><i class="bi bi-telephone me-1"></i><?= $canViewFullContact ? 'Call' : 'Login for Phone' ?></a><?php endif; ?>
          <a class="btn btn-outline-light btn-lg" href="<?=base_url('quotation-request.php?company_id='.(int)$co['id'])?>"><i class="bi bi-receipt me-1"></i>Request Quote</a>
          <a class="btn btn-primary btn-lg" href="#company-enquiry"><i class="bi bi-send me-1"></i>Send Enquiry</a>
          <?php if(!empty($bookingSettings['is_enabled']) || !empty($companyPageSettings['show_booking'])): ?><a class="btn btn-warning btn-lg" href="<?=base_url('appointments.php?company_id='.(int)$co['id'])?>"><i class="bi bi-calendar-check me-1"></i>Book Appointment</a><?php endif; ?>
        </div>
      </div>
      <div class="col-lg-4 text-lg-end">
        <img src="<?=e(!empty($co['logo']) ? base_url($co['logo']) : asset('images/company-hero.svg'))?>" class="img-fluid rounded-4 bg-white p-2 shadow" style="max-height:190px" alt="<?=e($co['name'])?>">
      </div>
    </div>
  </div>
</section>
<section class="mj-section"><div class="container">
  <?php show_flash(); ?>
  <?php if($isOwner || $isAdmin): ?>
    <div class="alert alert-<?=e(mj_company_status_badge_class($co['status']))?> rounded-4 d-flex flex-wrap justify-content-between align-items-center gap-2">
      <span><b>Status:</b> <?=e(mj_company_status_label($co['status']))?><?php if(($co['status'] ?? '')==='rejected'): ?> — <?=e(($co['rejection_reason'] ?? '') ?: 'Please update your company details.')?><?php endif; ?></span>
      <?php if($isOwner): ?><a class="btn btn-sm btn-dark" href="<?=base_url('company-edit.php?id='.(int)$co['id'])?>">Edit Company</a><?php endif; ?>
      <?php if($isAdmin): ?><a class="btn btn-sm btn-dark" href="<?=base_url('admin/company-edit.php?id='.(int)$co['id'])?>">Admin Edit</a><?php endif; ?>
    </div>
  <?php endif; ?>

  <?php if(!$canViewFullContact): ?>
    <div class="company-privacy-alert mb-4">
      <div class="d-flex align-items-start gap-3">
        <span class="company-privacy-icon"><i class="bi bi-shield-lock"></i></span>
        <div class="flex-grow-1">
          <b>Contact details are protected</b>
          <p class="mb-0">Phone, mobile and email are partially hidden for visitors. Login to view full contact details and contact this company safely.</p>
        </div>
        <a class="btn btn-primary" href="<?=e($loginUrl)?>">Login to view</a>
      </div>
    </div>
  <?php endif; ?>

  <div class="row g-4 company-layout-grid">
    <div class="col-lg-8">
      <div class="company-main-stack">
        <div class="mj-card p-4">
          <h3 class="fw-bold">About this company</h3>
          <p class="mb-0"><?=nl2br(e($co['description'] ?: 'No company description added yet.'))?></p>
        </div>

        <div class="mj-card p-4">
          <div class="d-flex justify-content-between align-items-center mb-3"><h3 class="fw-bold mb-0">Services Offered</h3><span class="badge bg-light text-dark"><?=e($serviceCount)?> services</span></div>
          <?php if(!$services): ?><p class="text-muted mb-0">No services added yet. Contact the company for more information.</p><?php else: ?><div class="row g-3"><?php foreach($services as $s): ?><div class="col-md-6"><div class="border rounded-4 p-3 h-100"><b><?=e($s['name'] ?? 'Service')?></b><?php if((float)($s['price_from'] ?? 0)>0 || !empty($s['duration_minutes'])): ?><p class="text-muted small mb-2"><?=((float)($s['price_from'] ?? 0)>0)?'From '.money($s['price_from'],$co['currency_code']??'USD'):''?> <?=!empty($s['duration_minutes'])?'• '.e($s['duration_minutes']).' mins':''?></p><?php endif; ?><p class="mb-0 small"><?=e($s['description'] ?? '')?></p></div></div><?php endforeach; ?></div><?php endif; ?>
        </div>


        <?php if(!empty($companySections)): ?>
        <!-- Flexible Company Sections v2.8.8 -->
        <?php foreach($companySections as $sec): ?>
          <div class="company-section-block">
            <h3 class="fw-bold mb-2"><?=e($sec['section_title'] ?: ucwords(str_replace('_',' ', $sec['section_key'])))?></h3>
            <div class="text-muted"><?=nl2br(e($sec['section_content'] ?? ''))?></div>
          </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <div class="company-contact-showcase">
          <div class="company-listings-heading mb-3">
            <div>
              <span class="mj-badge good mb-2"><i class="bi bi-person-lines-fill"></i> Quick contact</span>
              <h2>Contact this Company</h2>
              <p>Choose phone, mobile or email. Contact details are protected for visitors and fully visible after login.</p>
            </div>
          </div>
          <div class="company-contact-grid">
            <div class="company-contact-tile <?= $canViewFullContact ? 'is-visible' : 'is-masked' ?>">
              <span class="company-contact-tile-icon"><i class="bi bi-telephone-fill"></i></span>
              <span class="company-contact-label">Phone</span>
              <strong class="company-contact-value"><?=e(mj_contact_public_value($phoneValue, 'phone', $canViewFullContact))?></strong>
              <a class="company-contact-action" href="<?=e(mj_company_contact_action_url($phoneValue, 'phone', $canViewFullContact, $loginUrl))?>"><?= $canViewFullContact ? 'Call now' : 'Login to view' ?></a>
              <span class="company-contact-tooltip"><?= $canViewFullContact ? 'Full phone number is visible.' : 'Login to view full phone number.' ?></span>
            </div>
            <div class="company-contact-tile <?= $canViewFullContact ? 'is-visible' : 'is-masked' ?>">
              <span class="company-contact-tile-icon whatsapp"><i class="bi bi-whatsapp"></i></span>
              <span class="company-contact-label">Mobile / WhatsApp</span>
              <strong class="company-contact-value"><?=e(mj_contact_public_value($mobileOrWhatsapp, 'phone', $canViewFullContact))?></strong>
              <a class="company-contact-action success" href="<?=e($canViewFullContact && $waNumber ? ('https://wa.me/'.$waNumber.'?text='.$waMsg) : $loginUrl)?>" <?= $canViewFullContact && $waNumber ? 'target="_blank"' : '' ?>><?= $canViewFullContact ? 'WhatsApp' : 'Login to view' ?></a>
              <span class="company-contact-tooltip"><?= $canViewFullContact ? 'Full mobile / WhatsApp number is visible.' : 'Login to view full mobile / WhatsApp number.' ?></span>
            </div>
            <div class="company-contact-tile <?= $canViewFullContact ? 'is-visible' : 'is-masked' ?>">
              <span class="company-contact-tile-icon email"><i class="bi bi-envelope-fill"></i></span>
              <span class="company-contact-label">Email</span>
              <strong class="company-contact-value"><?=e(mj_contact_public_value($emailValue, 'email', $canViewFullContact))?></strong>
              <a class="company-contact-action" href="<?=e(mj_company_contact_action_url($emailValue, 'email', $canViewFullContact, $loginUrl))?>"><?= $canViewFullContact ? 'Send email' : 'Login to view' ?></a>
              <span class="company-contact-tooltip"><?= $canViewFullContact ? 'Full email address is visible.' : 'Login to view full email address.' ?></span>
            </div>
          </div>
        </div>

        <?php if($listings): ?>
          <div class="company-listings-section company-listings-inline">
            <div class="company-listings-heading">
              <div>
                <span class="mj-badge good mb-2"><i class="bi bi-shop"></i> Company listings</span>
                <h2>Active Listings from this Company</h2>
                <p>Browse products, services and offers posted by this company. Open any listing to view photos, price, details and contact options.</p>
              </div>
              <a class="btn btn-outline-primary" href="<?=base_url('browse.php?company_id='.(int)$co['id'])?>">View all listings</a>
            </div>
            <div class="company-listings-grid">
              <?php foreach($listings as $r): ?>
                <div class="company-listing-item"><?php include __DIR__.'/partials/listing-card.php'; ?></div>
              <?php endforeach; ?>
            </div>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="col-lg-4">
      <div class="company-sidebar-stack">

        <div class="mj-card p-4 mb-4" id="company-enquiry">
          <h3 class="fw-bold mb-1"><i class="bi bi-send me-1"></i>Send Enquiry</h3>
          <p class="text-muted small mb-3">Send your question or service request. The company owner will see this in their CRM / Leads inbox.</p>
          <form method="post" class="mj-clean-form">
            <?=csrf_input()?>
            <input type="hidden" name="action" value="company_enquiry">
            <div class="mb-2"><label class="form-label small fw-bold">Name *</label><input class="form-control" name="name" required value="<?=e($user['name'] ?? '')?>"></div>
            <div class="row g-2">
              <div class="col-md-6 mb-2"><label class="form-label small fw-bold">Email</label><input class="form-control" type="email" name="email" value="<?=e($user['email'] ?? '')?>"></div>
              <div class="col-md-6 mb-2"><label class="form-label small fw-bold">Phone / WhatsApp</label><input class="form-control" name="phone" value="<?=e($user['mobile'] ?? '')?>"></div>
            </div>
            <div class="mb-2"><label class="form-label small fw-bold">Service interested</label><input class="form-control" name="service_interested" placeholder="Example: data recovery, facial service, repair"></div>
            <div class="mb-2"><label class="form-label small fw-bold">Preferred contact</label><select class="form-select" name="preferred_contact"><option value="">Any method</option><option value="whatsapp">WhatsApp</option><option value="call">Call</option><option value="email">Email</option></select></div>
            <div class="mb-3"><label class="form-label small fw-bold">Message *</label><textarea class="form-control" name="message" rows="4" required>I am interested in your company/services. Please contact me.</textarea></div>
            <button class="btn btn-primary w-100 rounded-pill"><i class="bi bi-send me-1"></i>Send Enquiry</button>
          </form>
          <div class="alert alert-info small mt-3 mb-0 rounded-4"><i class="bi bi-shield-check me-1"></i>MJ Marketplace does not collect customer payment for company enquiries. The company will contact you directly.</div>
        </div>

        <div class="mj-card p-4 mb-4 company-contact-sidebar">
          <h3 class="fw-bold">Contact Information</h3>
          <div class="vstack gap-3">
            <div class="company-mini-contact <?= $canViewFullContact ? 'is-visible' : 'is-masked' ?>"><b><i class="bi bi-telephone me-1"></i>Phone</b><br><span class="text-muted"><?=e(mj_contact_public_value($phoneValue, 'phone', $canViewFullContact))?></span></div>
            <div class="company-mini-contact <?= $canViewFullContact ? 'is-visible' : 'is-masked' ?>"><b><i class="bi bi-phone me-1"></i>Mobile / WhatsApp</b><br><span class="text-muted"><?=e(mj_contact_public_value($mobileOrWhatsapp, 'phone', $canViewFullContact))?></span></div>
            <div class="company-mini-contact <?= $canViewFullContact ? 'is-visible' : 'is-masked' ?>"><b><i class="bi bi-envelope me-1"></i>Email</b><br><?php if($emailValue !== ''): ?><a href="<?=e(mj_company_contact_action_url($emailValue, 'email', $canViewFullContact, $loginUrl))?>"><?=e(mj_contact_public_value($emailValue, 'email', $canViewFullContact))?></a><?php else: ?><span class="text-muted">-</span><?php endif; ?></div>
            <div><b><i class="bi bi-globe me-1"></i>Website</b><br><?php if(!empty($co['website'])): ?><a href="<?=e($co['website'])?>" target="_blank" rel="nofollow noopener">Visit website</a><?php else: ?><span class="text-muted">-</span><?php endif; ?></div>
            <div><b><i class="bi bi-geo-alt me-1"></i>Address</b><br><span class="text-muted"><?=nl2br(e($co['address'] ?: '-'))?></span></div>
          </div>
          <?php if(!$canViewFullContact): ?><a class="btn btn-sm btn-primary w-100 mt-3" href="<?=e($loginUrl)?>"><i class="bi bi-unlock me-1"></i>Login to view full contact</a><?php endif; ?>
        </div>
        <div class="mj-card p-4 mb-4">
          <h3 class="fw-bold">Trust Center</h3>
          <div class="mb-3"><div class="d-flex justify-content-between small"><span>Profile completeness</span><b><?=e($profileScore)?>%</b></div><div class="progress" style="height:8px"><div class="progress-bar" style="width:<?=e($profileScore)?>%"></div></div></div>
          <div class="mb-3"><div class="d-flex justify-content-between small"><span>Trust score</span><b><?=e($trustScore)?>%</b></div><div class="progress" style="height:8px"><div class="progress-bar bg-success" style="width:<?=e($trustScore)?>%"></div></div></div>
          <ul class="list-unstyled mb-0 small">
            <li><i class="bi <?=!empty($co['is_verified'])?'bi-check-circle-fill text-success':'bi-circle text-muted'?> me-1"></i>Company verification</li>
            <li><i class="bi <?=!empty($phoneValue) || !empty($mobileOrWhatsapp)?'bi-check-circle-fill text-success':'bi-circle text-muted'?> me-1"></i>Phone / mobile added</li>
            <li><i class="bi <?=!empty($emailValue)?'bi-check-circle-fill text-success':'bi-circle text-muted'?> me-1"></i>Email added</li>
            <li><i class="bi <?=!empty($co['website'])?'bi-check-circle-fill text-success':'bi-circle text-muted'?> me-1"></i>Website added</li>
            <li><i class="bi <?=!empty($co['address'])?'bi-check-circle-fill text-success':'bi-circle text-muted'?> me-1"></i>Address added</li>
          </ul>
        </div>
        <div class="mj-card p-4 mb-4">
          <h3 class="fw-bold">Branches & Opening Hours</h3>
          <?php foreach($branches as $b): ?><div class="alert <?=open_status($b)==='Open now'?'alert-success':'alert-light'?> rounded-4"><b><?=e($b['name'] ?? 'Branch')?></b> <span class="badge text-bg-light"><?=e(open_status($b))?></span><br><span class="text-muted small"><?=e($b['address'] ?? '')?><br><?=e(local_datetime(date('Y-m-d H:i:s'), $b['timezone'] ?? 'UTC'))?></span></div><?php endforeach; if(!$branches): ?><p class="text-muted">No branch details added yet.</p><?php endif; ?>
          <div class="mj-map-card" data-mj-map data-lat="<?=e($co['latitude'] ?: '1.3521')?>" data-lng="<?=e($co['longitude'] ?: '103.8198')?>"></div>
        </div>
        <div class="mj-card p-4">
          <h3 class="fw-bold">Share this company</h3>
          <p class="text-muted small">Send this company profile to friends, customers or your team.</p>
          <div class="d-grid gap-2"><button class="btn btn-outline-primary" onclick="navigator.clipboard&&navigator.clipboard.writeText('<?=e($shareUrl)?>');this.innerHTML='Link copied';"><i class="bi bi-link-45deg me-1"></i>Copy Company Link</button><?php if($waNumber): ?><a class="btn btn-outline-success" target="_blank" href="https://wa.me/?text=<?=e(rawurlencode($co['name'].' - '.$shareUrl))?>"><i class="bi bi-whatsapp me-1"></i>Share by WhatsApp</a><?php endif; ?></div>
        </div>
      </div>
    </div>
  </div>
</div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
