<?php
require_once __DIR__.'/../includes/functions.php';
$admin = require_admin();
$adminTitle = 'Companies';
verify_csrf();
mj_company_module_ensure_schema(); mj_review_ensure_schema();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    $ids = [];
    if (!empty($_POST['ids']) && is_array($_POST['ids'])) {
        foreach ($_POST['ids'] as $rawId) { $ids[] = (int)$rawId; }
    } elseif (!empty($_POST['id'])) {
        $ids[] = (int)$_POST['id'];
    }
    $ids = array_values(array_filter(array_unique($ids)));
    if (!$ids) { flash('warning', 'Please choose at least one company.'); redirect('companies.php'); }

    $statusActions = ['active','pending','rejected','suspended','draft'];
    $updated = 0;
    foreach ($ids as $companyId) {
        $old = one('SELECT id,status FROM mj_companies WHERE id=? LIMIT 1', [$companyId]);
        if (!$old) { continue; }
        if ($action === 'verify') {
            $data = mj_company_filter_columns_fresh('mj_companies', [
                'is_verified'=>1,
                'verification_status'=>'verified',
                'status'=>'active',
                'last_reviewed_at'=>date('Y-m-d H:i:s'),
                'last_reviewed_by'=>(int)($admin['id'] ?? 0)
            ]);
        } elseif ($action === 'unverify') {
            $data = mj_company_filter_columns_fresh('mj_companies', [
                'is_verified'=>0,
                'verification_status'=>'not_verified',
                'last_reviewed_at'=>date('Y-m-d H:i:s'),
                'last_reviewed_by'=>(int)($admin['id'] ?? 0)
            ]);
        } elseif ($action === 'feature') {
            $data = mj_company_filter_columns_fresh('mj_companies', ['is_featured'=>1]);
        } elseif ($action === 'unfeature') {
            $data = mj_company_filter_columns_fresh('mj_companies', ['is_featured'=>0]);
        } elseif (in_array($action, $statusActions, true)) {
            $reason = mj_company_clean($_POST['rejection_reason'] ?? '', 5000);
            if ($action === 'rejected' && $reason === '') { $reason = 'Please review and update your company profile details.'; }
            $data = mj_company_filter_columns_fresh('mj_companies', [
                'status'=>$action,
                'rejection_reason'=>$action === 'rejected' ? $reason : null,
                'last_reviewed_at'=>date('Y-m-d H:i:s'),
                'last_reviewed_by'=>(int)($admin['id'] ?? 0)
            ]);
        } else {
            continue;
        }
        if ($data) {
            $sets=[]; $params=[];
            foreach($data as $k=>$v){ $sets[]='`'.$k.'`=?'; $params[]=$v; }
            $params[]=$companyId;
            q('UPDATE mj_companies SET '.implode(',', $sets).', updated_at=NOW() WHERE id=?', $params);
            mj_company_update_scores($companyId);
            mj_company_timeline_add($companyId, 'admin', (int)($admin['id'] ?? 0), 'admin_'.$action, 'Company action: '.$action, (string)($old['status'] ?? ''), $data['status'] ?? (string)($old['status'] ?? ''));
            $updated++;
        }
    }
    admin_log('company_bulk_action', 'mj_companies', 0, ['action'=>$action, 'ids'=>$ids]);
    flash('success', $updated.' company record(s) updated.');
    redirect('companies.php');
}

$status = $_GET['status'] ?? '';
$country = (int)($_GET['country_id'] ?? 0);
$verified = (string)($_GET['verified'] ?? '');
$qtext = trim((string)($_GET['q'] ?? ''));
$where = ['1=1'];
$params = [];
if ($status !== '') { $where[] = 'co.status=?'; $params[] = $status; }
if ($country) { $where[] = 'co.country_id=?'; $params[] = $country; }
if ($verified === '1') { $where[] = 'co.is_verified=1'; }
if ($verified === '0') { $where[] = 'co.is_verified=0'; }
if ($qtext !== '') {
    $where[] = '(co.name LIKE ? OR co.email LIKE ? OR co.phone LIKE ? OR co.whatsapp LIKE ? OR co.website LIKE ? OR u.name LIKE ?)';
    for ($i=0;$i<6;$i++) { $params[] = '%'.$qtext.'%'; }
}
$rows = all_rows("SELECT co.*,u.name user_name,u.email user_email,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_listings l WHERE l.company_id=co.id AND l.status IN ('active','approved','published')) active_listing_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_users u ON u.id=co.user_id
    LEFT JOIN mj_countries c ON c.id=co.country_id
    LEFT JOIN mj_categories cat ON cat.id=co.category_id
    WHERE ".implode(' AND ', $where).' ORDER BY co.id DESC LIMIT 500', $params);
$countries = all_rows('SELECT id,name,flag_emoji FROM mj_countries WHERE is_active=1 ORDER BY name');
$stats = [
    'all' => safe_count('SELECT COUNT(*) c FROM mj_companies'),
    'active' => safe_count('SELECT COUNT(*) c FROM mj_companies WHERE status="active"'),
    'pending' => safe_count('SELECT COUNT(*) c FROM mj_companies WHERE status="pending"'),
    'verified' => safe_count('SELECT COUNT(*) c FROM mj_companies WHERE is_verified=1'),
    'updates' => function_exists('mj_review_pending_count') ? mj_review_pending_count('company') : safe_count('SELECT COUNT(*) c FROM mj_company_revisions WHERE status="pending"'),
];
include __DIR__.'/_header.php';
?>
<div class="row">
  <div class="col-lg-3 col-6"><div class="small-box bg-info"><div class="inner"><h3><?=e($stats['all'])?></h3><p>Total companies</p></div><div class="icon"><i class="fas fa-building"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-success"><div class="inner"><h3><?=e($stats['active'])?></h3><p>Active</p></div><div class="icon"><i class="fas fa-check-circle"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-warning"><div class="inner"><h3><?=e($stats['pending'])?></h3><p>Pending review</p></div><div class="icon"><i class="fas fa-hourglass-half"></i></div></div></div>
  <div class="col-lg-3 col-6"><a href="company-revisions.php" class="small-box bg-primary d-block text-white"><div class="inner"><h3><?=e($stats['updates'])?></h3><p>Pending Updates</p></div><div class="icon"><i class="fas fa-code-branch"></i></div></a></div>
</div>

<div class="card card-primary card-outline">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-building mr-2"></i>Manage Companies</h3>
    <div class="card-tools"><a href="company-revisions.php" class="btn btn-sm btn-warning"><i class="fas fa-code-branch"></i> Pending Updates</a> <a href="../add-company.php" target="_blank" class="btn btn-sm btn-primary"><i class="fas fa-plus"></i> Add Company</a></div>
  </div>
  <div class="card-body">
    <div class="alert alert-info rounded"><i class="fas fa-info-circle mr-1"></i> Review company details, help users complete profiles, verify trusted companies, and keep public company pages clean.</div>
    <form class="form-row mb-3" method="get">
      <div class="col-md-3 mb-2"><input name="q" class="form-control" value="<?=e($qtext)?>" placeholder="Search company, owner, phone, email"></div>
      <div class="col-md-2 mb-2"><select name="status" class="form-control"><option value="">All status</option><?php foreach(['draft','pending','active','rejected','suspended'] as $s): ?><option value="<?=$s?>" <?=$status===$s?'selected':''?>><?=e(mj_company_status_label($s))?></option><?php endforeach; ?></select></div>
      <div class="col-md-3 mb-2"><select name="country_id" class="form-control"><option value="">All countries</option><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>" <?=$country==(int)$c['id']?'selected':''?>><?=e($c['flag_emoji'].' '.$c['name'])?></option><?php endforeach; ?></select></div>
      <div class="col-md-2 mb-2"><select name="verified" class="form-control"><option value="">All verification</option><option value="1" <?=$verified==='1'?'selected':''?>>Verified only</option><option value="0" <?=$verified==='0'?'selected':''?>>Not verified</option></select></div>
      <div class="col-md-2 mb-2"><button class="btn btn-info btn-block"><i class="fas fa-filter"></i> Filter</button></div>
    </form>

    <form method="post" id="companyBulkForm">
      <?=csrf_input()?>
      <div class="d-flex flex-wrap align-items-center mb-3" style="gap:8px">
        <select name="action" class="form-control form-control-sm" style="max-width:220px" required>
          <option value="">Bulk action</option>
          <option value="active">Approve / Active</option>
          <option value="pending">Move to Pending Review</option>
          <option value="verify">Verify + Approve</option>
          <option value="unverify">Remove Verified</option>
          <option value="feature">Mark Featured</option>
          <option value="unfeature">Remove Featured</option>
          <option value="rejected">Reject / Needs Update</option>
          <option value="suspended">Suspend</option>
        </select>
        <input name="rejection_reason" class="form-control form-control-sm" style="max-width:360px" placeholder="Reject reason, if rejecting">
        <button class="btn btn-sm btn-secondary"><i class="fas fa-check-square"></i> Apply</button>
      </div>
      <div class="table-responsive">
        <table class="table table-striped table-hover mj-data-table">
          <thead><tr><th><input type="checkbox" onclick="document.querySelectorAll('.company-check').forEach(x=>x.checked=this.checked)"></th><th>ID</th><th>Company</th><th>Owner</th><th>Country</th><th>Contact</th><th>Status</th><th>Quality</th><th>Listings</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach($rows as $r): $profile=(int)($r['profile_score'] ?? mj_company_profile_score($r)); $trust=(int)($r['trust_score'] ?? mj_company_trust_score($r)); ?>
            <tr>
              <td><input class="company-check" type="checkbox" name="ids[]" value="<?=e($r['id'])?>"></td>
              <td><?=e($r['id'])?></td>
              <td><a href="company-edit.php?id=<?=e($r['id'])?>"><b><?=e($r['name'])?></b></a><br><small class="text-muted"><?=e($r['category'] ?: 'No category')?> <?=!empty($r['is_featured'])?'• Featured':''?> <?=!empty($r['is_sponsored'])?'• Sponsored':''?></small><?php if((int)($r['pending_update_count']??0)>0): ?><br><a class="badge badge-warning" href="company-revisions.php">Pending update review</a><?php endif; ?></td>
              <td><?=e($r['user_name'] ?: '-')?><br><small class="text-muted"><?=e($r['user_email'] ?: '')?></small></td>
              <td><?=e(($r['flag_emoji'] ?? '').' '.($r['country'] ?? ''))?></td>
              <td><?=e($r['phone'] ?: $r['whatsapp'] ?: '-')?><br><small><?=e($r['email'] ?: '')?></small></td>
              <td><span class="badge badge-<?=e(mj_company_status_badge_class($r['status']))?>"><?=e(mj_company_status_label($r['status']))?></span><br><?=!empty($r['is_verified'])?'<span class="badge badge-success mt-1">Verified</span>':'<span class="badge badge-secondary mt-1">Not verified</span>'?></td>
              <td><small>Profile <?=e($profile)?>%</small><div class="progress" style="height:6px"><div class="progress-bar bg-info" style="width:<?=e($profile)?>%"></div></div><small>Trust <?=e($trust)?>%</small></td>
              <td><?=e($r['active_listing_count'])?> active<br><small class="text-muted"><?=e($r['listing_count'])?> total</small></td>
              <td>
                <div class="btn-group btn-group-sm mb-1"><a href="company-edit.php?id=<?=e($r['id'])?>" class="btn btn-primary"><i class="fas fa-edit"></i> Edit</a><a href="../company.php?id=<?=e($r['id'])?>" target="_blank" class="btn btn-info"><i class="fas fa-eye"></i></a></div>
                <div class="btn-group btn-group-sm">
                  <button type="submit" name="action" value="active" formaction="companies.php" onclick="this.form.querySelectorAll('.company-check').forEach(x=>x.checked=false); this.form.insertAdjacentHTML('beforeend','<input type=&quot;hidden&quot; name=&quot;id&quot; value=&quot;<?=e($r['id'])?>&quot;>')" class="btn btn-success">Approve</button>
                  <button type="submit" name="action" value="verify" formaction="companies.php" onclick="this.form.querySelectorAll('.company-check').forEach(x=>x.checked=false); this.form.insertAdjacentHTML('beforeend','<input type=&quot;hidden&quot; name=&quot;id&quot; value=&quot;<?=e($r['id'])?>&quot;>')" class="btn btn-outline-info">Verify</button>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </form>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
