<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
mj_company_module_ensure_schema(); mj_review_ensure_schema();
if(function_exists('mj_quote_ensure_schema')){ mj_quote_ensure_schema(); }
$pageTitle = 'My Companies';
$rows = all_rows("SELECT co.*, c.name country, c.flag_emoji, cat.name category,
    (SELECT COUNT(*) FROM mj_listings l WHERE l.company_id=co.id) listing_count,
    (SELECT COUNT(*) FROM mj_company_services s WHERE s.company_id=co.id) service_count,
    (SELECT COUNT(*) FROM mj_quote_requests qr WHERE qr.company_id=co.id) quote_count,
    (SELECT COUNT(*) FROM mj_quote_requests qr WHERE qr.company_id=co.id AND qr.status IN ('new','reviewed','follow_up')) open_quote_count,
    (SELECT COUNT(*) FROM mj_company_revisions cr WHERE cr.company_id=co.id AND cr.status='pending') pending_update_count
    FROM mj_companies co
    LEFT JOIN mj_countries c ON c.id=co.country_id
    LEFT JOIN mj_categories cat ON cat.id=co.category_id
    WHERE co.user_id=? ORDER BY co.id DESC", [(int)$u['id']]);
include __DIR__.'/includes/header.php';
?>
<section class="mj-section"><div class="container">
  <div class="row g-4">
    <div class="col-lg-3"><?php include __DIR__.'/includes/account-sidebar.php'; ?></div>
    <div class="col-lg-9">
      <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
        <div><h1 class="mb-1">My Companies</h1><p class="text-muted mb-0">Manage your company profiles, improve details and keep your business visible to buyers.</p></div>
        <a href="<?=base_url('add-company.php')?>" class="btn btn-primary"><i class="bi bi-plus-circle me-1"></i>Add Company Profile</a>
      </div>
      <?php if(!$rows): ?>
        <div class="mj-card p-5 text-center">
          <div class="display-6 mb-3"><i class="bi bi-building-add"></i></div>
          <h3>You have not added a company profile yet</h3>
          <p class="text-muted">Create a company profile to show your services, contact details, active listings and promotions.</p>
          <a href="<?=base_url('add-company.php')?>" class="btn btn-primary btn-lg">Add Company Profile</a>
        </div>
      <?php else: ?>
        <div class="row g-4">
          <?php foreach($rows as $r):
            $profile = (int)($r['profile_score'] ?? mj_company_profile_score($r, (int)$r['service_count']));
            $trust = (int)($r['trust_score'] ?? mj_company_trust_score($r, (int)$r['service_count']));
          ?>
            <div class="col-12">
              <div class="mj-card p-4">
                <div class="row g-3 align-items-center">
                  <div class="col-md-2 text-center">
                    <img src="<?=e(!empty($r['logo']) ? base_url($r['logo']) : asset('images/company-hero.svg'))?>" class="img-fluid rounded-4 border bg-white p-2" style="max-height:92px" alt="<?=e($r['name'])?>">
                  </div>
                  <div class="col-md-5">
                    <div class="d-flex flex-wrap gap-2 mb-2">
                      <span class="badge bg-<?=e(mj_company_status_badge_class($r['status']))?>"><?=e(mj_company_status_label($r['status']))?></span>
                      <?php if(!empty($r['is_verified'])): ?><span class="badge bg-success"><i class="bi bi-patch-check-fill me-1"></i>Verified</span><?php endif; ?>
                      <?php if(!empty($r['is_featured'])): ?><span class="badge bg-warning text-dark">Featured</span><?php endif; ?>
                      <?php if((int)($r['pending_update_count'] ?? 0)>0): ?><span class="badge bg-info text-dark">Pending Update Review</span><?php endif; ?>
                    </div>
                    <h4 class="fw-bold mb-1"><?=e($r['name'])?></h4>
                    <p class="text-muted mb-1"><?=e(($r['flag_emoji'] ?? '').' '.($r['country'] ?? ''))?> <?=!empty($r['category'])?'• '.e($r['category']):''?></p>
                    <?php if(($r['status'] ?? '') === 'rejected'): ?><div class="alert alert-warning py-2 mb-0"><b>Needs update:</b> <?=e(($r['rejection_reason'] ?? '') ?: 'Please review and submit again.')?></div><?php endif; ?>
                    <?php if(($r['status'] ?? '') === 'pending'): ?><div class="text-info small"><i class="bi bi-hourglass-split me-1"></i>Under review. You can still improve your profile while waiting.</div><?php endif; ?>
                  </div>
                  <div class="col-md-3">
                    <div class="mb-2"><div class="d-flex justify-content-between small"><span>Profile</span><b><?=e($profile)?>%</b></div><div class="progress" style="height:7px"><div class="progress-bar" style="width:<?=e($profile)?>%"></div></div></div>
                    <div><div class="d-flex justify-content-between small"><span>Trust</span><b><?=e($trust)?>%</b></div><div class="progress" style="height:7px"><div class="progress-bar bg-success" style="width:<?=e($trust)?>%"></div></div></div>
                    <div class="small text-muted mt-2"><?=e($r['listing_count'])?> listings • <?=e($r['service_count'])?> services • <?=e($r['views'])?> views</div>
                    <?php if((int)($r['quote_count'] ?? 0)>0): ?>
                      <div class="small mt-1"><a class="text-decoration-none fw-bold" href="<?=base_url('company-quotes.php?company_id='.(int)$r['id'])?>"><i class="bi bi-receipt-cutoff me-1"></i><?=e((int)$r['quote_count'])?> quote request<?=((int)$r['quote_count']===1?'':'s')?><?=((int)($r['open_quote_count'] ?? 0)>0?' • '.e((int)$r['open_quote_count']).' open':'')?></a></div>
                    <?php endif; ?>
                  </div>
                  <div class="col-md-2 text-md-end">
                    <a class="btn btn-primary btn-sm mb-2 w-100" href="<?=base_url('company-edit.php?id='.(int)$r['id'])?>"><i class="bi bi-pencil-square me-1"></i>Edit</a>
                    <a class="btn btn-outline-secondary btn-sm mb-2 w-100" target="_blank" href="<?=e(mj_company_public_url($r))?>"><i class="bi bi-eye me-1"></i>View</a>
                    <a class="btn <?=((int)($r['open_quote_count'] ?? 0)>0?'btn-warning':'btn-outline-warning')?> btn-sm mb-2 w-100" href="<?=base_url('company-quotes.php?company_id='.(int)$r['id'])?>"><i class="bi bi-receipt-cutoff me-1"></i>Quote Requests<?=((int)($r['open_quote_count'] ?? 0)>0?' ('.e((int)$r['open_quote_count']).')':'')?></a>
                    <a class="btn btn-outline-primary btn-sm w-100" href="<?=base_url('post-listing.php?company_id='.(int)$r['id'])?>"><i class="bi bi-plus-circle me-1"></i>Add Listing</a>
                  </div>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
