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

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$co = $id > 0 ? one('SELECT * FROM mj_companies WHERE id=? LIMIT 1', [$id]) : null;
if (!$co) { flash('error', 'Company not found.'); redirect('companies.php'); }

$countries = all_rows('SELECT id,name,flag_emoji,timezone_default FROM mj_countries WHERE is_active=1 ORDER BY name');
$cats = all_rows('SELECT id,name FROM mj_categories WHERE type="company" AND is_active=1 ORDER BY sort_order,name');
$users = all_rows('SELECT id,name,email FROM mj_users ORDER BY id DESC LIMIT 500');
$ownerFound = false; foreach ($users as $uu) { if ((int)$uu['id'] === (int)$co['user_id']) { $ownerFound = true; break; } }
if (!$ownerFound && !empty($co['user_id'])) { $ownerRow = one('SELECT id,name,email FROM mj_users WHERE id=? LIMIT 1', [(int)$co['user_id']]); if ($ownerRow) { array_unshift($users, $ownerRow); } }
$serviceText = mj_company_get_services_text($id);
$mainBranch = one('SELECT * FROM mj_company_branches WHERE company_id=? ORDER BY is_main DESC,id LIMIT 1', [$id]);
$hours = json_decode((string)($mainBranch['opening_hours_json'] ?? ''), true) ?: [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $oldStatus = (string)($co['status'] ?? '');
    $data = [
        'user_id' => (int)($_POST['user_id'] ?? $co['user_id']),
        'category_id' => !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null,
        'country_id' => (int)($_POST['country_id'] ?? 0),
        'state_id' => !empty($_POST['state_id']) ? (int)$_POST['state_id'] : null,
        'city_id' => !empty($_POST['city_id']) ? (int)$_POST['city_id'] : null,
        'timezone' => mj_company_clean($_POST['timezone'] ?? ($co['timezone'] ?? 'UTC'), 80),
        'name' => mj_company_clean($_POST['name'] ?? '', 220),
        'registration_no' => mj_company_clean($_POST['registration_no'] ?? '', 120),
        'description' => mj_company_clean($_POST['description'] ?? '', 20000),
        'phone' => mj_company_clean($_POST['phone'] ?? '', 80),
        'whatsapp' => mj_company_clean($_POST['whatsapp'] ?? '', 80),
        'email' => mj_company_clean($_POST['email'] ?? '', 190),
        'website' => mj_company_normalize_url((string)($_POST['website'] ?? '')),
        'address' => mj_company_clean($_POST['address'] ?? '', 5000),
        'latitude' => ($_POST['latitude'] ?? '') !== '' ? (float)$_POST['latitude'] : null,
        'longitude' => ($_POST['longitude'] ?? '') !== '' ? (float)$_POST['longitude'] : null,
        'status' => in_array(($_POST['status'] ?? 'pending'), ['draft','pending','active','rejected','suspended'], true) ? $_POST['status'] : 'pending',
        'is_verified' => !empty($_POST['is_verified']) ? 1 : 0,
        'verification_status' => mj_company_clean($_POST['verification_status'] ?? 'not_verified', 40),
        'verification_until' => !empty($_POST['verification_until']) ? $_POST['verification_until'] : null,
        'is_featured' => !empty($_POST['is_featured']) ? 1 : 0,
        'is_sponsored' => !empty($_POST['is_sponsored']) ? 1 : 0,
        'sponsored_until' => !empty($_POST['sponsored_until']) ? str_replace('T', ' ', $_POST['sponsored_until']).':00' : null,
        'admin_note' => mj_company_clean($_POST['admin_note'] ?? '', 10000),
        'rejection_reason' => mj_company_clean($_POST['rejection_reason'] ?? '', 5000),
        'last_reviewed_at' => date('Y-m-d H:i:s'),
        'last_reviewed_by' => (int)($admin['id'] ?? 0),
    ];
    if ($data['status'] === 'rejected' && trim((string)$data['rejection_reason']) === '') {
        flash('error', 'Please add a reject reason so the user knows what to update.');
    } else {
        $errors = mj_company_validate_data($data);
        if ($errors) {
            foreach ($errors as $err) { flash('error', $err); }
        } else {
            try {
                if (!empty($_POST['slug'])) { $data['slug'] = mj_slug_unique('mj_companies', (string)$_POST['slug'], $id); }
                elseif (trim((string)$co['name']) !== $data['name']) { $data['slug'] = mj_slug_unique('mj_companies', $data['name'], $id); }
                if (!empty($_FILES['logo']['name'])) { $data['logo'] = upload_image('logo', 'companies/logos'); }
                if (!empty($_FILES['cover_image']['name'])) { $data['cover_image'] = upload_image('cover_image', 'companies/banners'); }

                $data = mj_company_filter_columns_fresh('mj_companies', $data);
                $sets = [];
                $params = [];
                foreach ($data as $k => $v) { $sets[] = '`'.$k.'`=?'; $params[] = $v; }
                $sets[] = 'updated_at=NOW()';
                $params[] = $id;
                q('UPDATE mj_companies SET '.implode(',', $sets).' WHERE id=?', $params);

                mj_company_update_main_branch($id, array_merge($data, [
                    'weekday_open' => $_POST['weekday_open'] ?? '09:00',
                    'weekday_close' => $_POST['weekday_close'] ?? '18:00',
                    'saturday_open' => $_POST['saturday_open'] ?? '09:00',
                    'saturday_close' => $_POST['saturday_close'] ?? '13:00',
                    'sunday_open' => $_POST['sunday_open'] ?? '09:00',
                    'sunday_close' => $_POST['sunday_close'] ?? '13:00',
                    'saturday_closed' => !empty($_POST['saturday_closed']),
                    'sunday_closed' => !empty($_POST['sunday_closed']),
                ]));
                $serviceCount = mj_company_save_services_from_text($id, (string)($_POST['services_text'] ?? ''));
                mj_company_update_scores($id);
                mj_company_timeline_add($id, 'admin', (int)($admin['id'] ?? 0), 'admin_update', 'Company updated from admin. Services saved: '.$serviceCount, $oldStatus, (string)$data['status']);
                admin_log('company_edit', 'mj_companies', $id, ['status'=>$data['status'] ?? '', 'old_status'=>$oldStatus]);
                flash('success', 'Company updated successfully.');
                redirect('company-edit.php?id='.$id);
            } catch (Throwable $e) {
                flash('error', $e->getMessage());
            }
        }
    }
    $co = one('SELECT * FROM mj_companies WHERE id=? LIMIT 1', [$id]);
    $serviceText = (string)($_POST['services_text'] ?? $serviceText);
}

$timeline = table_exists('mj_company_timeline') ? all_rows('SELECT * FROM mj_company_timeline WHERE company_id=? ORDER BY id DESC LIMIT 12', [$id]) : [];
$listingsCount = safe_count('SELECT COUNT(*) c FROM mj_listings WHERE company_id=?', [$id]);
$activeListings = safe_count('SELECT COUNT(*) c FROM mj_listings WHERE company_id=? AND status IN ("active","approved","published")', [$id]);
$profileScore = (int)($co['profile_score'] ?? mj_company_profile_score($co, substr_count($serviceText, "\n") + ($serviceText !== '' ? 1 : 0)));
$trustScore = (int)($co['trust_score'] ?? mj_company_trust_score($co));
include __DIR__.'/_header.php';
?>
<style>
.company-edit-page .card-title{font-weight:600;}
.company-edit-page .sticky-side{position:sticky;top:1rem;}
.company-edit-page .helper-text{font-size:.875rem;color:#6c757d;}
.company-edit-page .mini-stat{border:1px solid #e9ecef;border-radius:.5rem;padding:.75rem .9rem;background:#f8f9fa;height:100%;}
.company-edit-page .day-check{padding-top:2rem;}
@media (max-width: 991.98px){
  .company-edit-page .sticky-side{position:static;}
  .company-edit-page .day-check{padding-top:.25rem;}
}
</style>
<div class="company-edit-page">
<div class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-8">
        <h1 class="m-0"><i class="fas fa-building mr-2"></i>Edit Company</h1>
        <p class="text-muted mb-0">Update company profile, contact details, verification, sponsor settings and review status.</p>
      </div>
      <div class="col-sm-4 text-right">
        <a href="companies.php" class="btn btn-default"><i class="fas fa-arrow-left"></i> Companies</a>
        <a href="../company.php?id=<?=e($id)?>" target="_blank" class="btn btn-info"><i class="fas fa-external-link-alt"></i> View Public</a>
      </div>
    </div>
  </div>
</div>

<section class="content">
  <div class="container-fluid">
    <form method="post" enctype="multipart/form-data">
      <?=csrf_input()?>
      <input type="hidden" name="id" value="<?=e($id)?>">

      <div class="row">
        <div class="col-lg-8">
          <div class="card card-primary card-outline">
            <div class="card-header">
              <h3 class="card-title">Company details</h3>
            </div>
            <div class="card-body">
              <div class="alert alert-info">
                <i class="fas fa-info-circle mr-1"></i>
                Keep the profile clear and complete. This helps buyers trust the company and contact the right person faster.
              </div>

              <div class="form-row">
                <div class="form-group col-md-8">
                  <label>Company name <span class="text-danger">*</span></label>
                  <input name="name" class="form-control" maxlength="220" required value="<?=e($co['name'] ?? '')?>">
                </div>
                <div class="form-group col-md-4">
                  <label>Registration no.</label>
                  <input name="registration_no" class="form-control" maxlength="120" value="<?=e($co['registration_no'] ?? '')?>">
                </div>
              </div>

              <div class="form-row">
                <div class="form-group col-md-4">
                  <label>Owner</label>
                  <select name="user_id" class="form-control" required>
                    <?php foreach($users as $u): ?>
                      <option value="<?=e($u['id'])?>" <?=((int)$co['user_id']===(int)$u['id'])?'selected':''?>><?=e($u['name'].' - '.$u['email'])?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-group col-md-4">
                  <label>Country <span class="text-danger">*</span></label>
                  <select name="country_id" class="form-control" onchange="loadStates(this.value,'state_id')" required>
                    <option value="">Select country</option>
                    <?php foreach($countries as $c): ?>
                      <option value="<?=e($c['id'])?>" data-tz="<?=e($c['timezone_default'])?>" <?=((int)$co['country_id']===(int)$c['id'])?'selected':''?>><?=e($c['flag_emoji'].' '.$c['name'])?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-group col-md-4">
                  <label>Category <span class="text-danger">*</span></label>
                  <select name="category_id" class="form-control" required>
                    <option value="">Select category</option>
                    <?php foreach($cats as $cat): ?>
                      <option value="<?=e($cat['id'])?>" <?=((int)$co['category_id']===(int)$cat['id'])?'selected':''?>><?=e($cat['name'])?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>

              <div class="form-row">
                <div class="form-group col-md-4">
                  <label>State</label>
                  <select name="state_id" id="state_id" class="form-control" onchange="loadCities(this.value,'city_id')">
                    <option value="<?=e($co['state_id'] ?? '')?>"><?=!empty($co['state_id'])?'Current selected':'State'?></option>
                  </select>
                </div>
                <div class="form-group col-md-4">
                  <label>City</label>
                  <select name="city_id" id="city_id" class="form-control">
                    <option value="<?=e($co['city_id'] ?? '')?>"><?=!empty($co['city_id'])?'Current selected':'City'?></option>
                  </select>
                </div>
                <div class="form-group col-md-4">
                  <label>Timezone</label>
                  <input name="timezone" class="form-control" maxlength="80" value="<?=e($co['timezone'] ?? 'UTC')?>">
                </div>
              </div>

              <div class="form-group">
                <label>Business address <span class="text-danger">*</span></label>
                <textarea name="address" rows="3" class="form-control" required><?=e($co['address'] ?? '')?></textarea>
              </div>

              <div class="form-row">
                <div class="form-group col-md-6">
                  <label>Latitude</label>
                  <input name="latitude" class="form-control" value="<?=e($co['latitude'] ?? '')?>" placeholder="Optional">
                </div>
                <div class="form-group col-md-6">
                  <label>Longitude</label>
                  <input name="longitude" class="form-control" value="<?=e($co['longitude'] ?? '')?>" placeholder="Optional">
                </div>
              </div>

              <div class="form-row">
                <div class="form-group col-md-4">
                  <label>Phone</label>
                  <input name="phone" class="form-control" maxlength="80" value="<?=e($co['phone'] ?? '')?>">
                </div>
                <div class="form-group col-md-4">
                  <label>WhatsApp</label>
                  <input name="whatsapp" class="form-control" maxlength="80" value="<?=e($co['whatsapp'] ?? '')?>">
                </div>
                <div class="form-group col-md-4">
                  <label>Email</label>
                  <input name="email" type="email" class="form-control" maxlength="190" value="<?=e($co['email'] ?? '')?>">
                </div>
              </div>

              <div class="form-group">
                <label>Website</label>
                <input name="website" class="form-control" maxlength="255" placeholder="https://example.com" value="<?=e($co['website'] ?? '')?>">
                <small class="form-text text-muted">If you type example.com, the system will save it as https://example.com.</small>
              </div>

              <div class="form-group">
                <label>Description <span class="text-danger">*</span></label>
                <textarea name="description" rows="6" class="form-control" required minlength="20" placeholder="Tell users what the company does, service area, benefits and contact instruction."><?=e($co['description'] ?? '')?></textarea>
              </div>

              <div class="form-group">
                <label>Services offered</label>
                <textarea name="services_text" rows="5" class="form-control" placeholder="One service per line, e.g. Data Recovery&#10;SSD Recovery&#10;NAS Recovery"><?=e($serviceText)?></textarea>
                <small class="form-text text-muted">One service per line. These appear as service tags on the company profile.</small>
              </div>

              <div class="form-row">
                <div class="form-group col-md-6">
                  <label>Logo</label>
                  <input type="file" name="logo" class="form-control" accept="image/*">
                  <?php if(!empty($co['logo'])): ?>
                    <img src="<?=e(base_url($co['logo']))?>" class="img-thumbnail mt-2" style="max-height:80px" alt="Logo">
                  <?php endif; ?>
                </div>
                <div class="form-group col-md-6">
                  <label>Banner image</label>
                  <input type="file" name="cover_image" class="form-control" accept="image/*">
                  <?php if(!empty($co['cover_image'])): ?>
                    <img src="<?=e(base_url($co['cover_image']))?>" class="img-thumbnail mt-2" style="max-height:80px" alt="Banner">
                  <?php endif; ?>
                </div>
              </div>
            </div>
          </div>

          <div class="card card-outline card-secondary">
            <div class="card-header">
              <h3 class="card-title">Opening hours</h3>
            </div>
            <div class="card-body">
              <div class="form-row">
                <div class="form-group col-md-3">
                  <label>Weekday open</label>
                  <input type="time" name="weekday_open" class="form-control" value="<?=e($hours['mon']['open'] ?? '09:00')?>">
                </div>
                <div class="form-group col-md-3">
                  <label>Weekday close</label>
                  <input type="time" name="weekday_close" class="form-control" value="<?=e($hours['mon']['close'] ?? '18:00')?>">
                </div>
                <div class="form-group col-md-3">
                  <label>Saturday open</label>
                  <input type="time" name="saturday_open" class="form-control" value="<?=e($hours['sat']['open'] ?? '09:00')?>">
                </div>
                <div class="form-group col-md-3">
                  <label>Saturday close</label>
                  <input type="time" name="saturday_close" class="form-control" value="<?=e($hours['sat']['close'] ?? '13:00')?>">
                </div>
              </div>

              <div class="form-row">
                <div class="form-group col-md-3">
                  <label>Sunday open</label>
                  <input type="time" name="sunday_open" class="form-control" value="<?=e($hours['sun']['open'] ?? '09:00')?>">
                </div>
                <div class="form-group col-md-3">
                  <label>Sunday close</label>
                  <input type="time" name="sunday_close" class="form-control" value="<?=e($hours['sun']['close'] ?? '13:00')?>">
                </div>
                <div class="form-group col-md-3 day-check">
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="saturday_closed" name="saturday_closed" <?=!empty($hours['sat']['closed'])?'checked':''?>>
                    <label class="custom-control-label" for="saturday_closed">Saturday closed</label>
                  </div>
                </div>
                <div class="form-group col-md-3 day-check">
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="sunday_closed" name="sunday_closed" <?=!empty($hours['sun']['closed'])?'checked':''?>>
                    <label class="custom-control-label" for="sunday_closed">Sunday closed</label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-lg-4">
          <div class="sticky-side">
            <div class="card card-outline card-success">
              <div class="card-header">
                <h3 class="card-title">Review & visibility</h3>
              </div>
              <div class="card-body">
                <div class="form-group">
                  <label>Status</label>
                  <select name="status" class="form-control">
                    <?php foreach(['draft'=>'Draft','pending'=>'Pending Review','active'=>'Active','rejected'=>'Needs Update / Rejected','suspended'=>'Suspended'] as $k=>$v): ?>
                      <option value="<?=e($k)?>" <?=$co['status']===$k?'selected':''?>><?=e($v)?></option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div class="form-group">
                  <label>Reject / update reason</label>
                  <textarea name="rejection_reason" class="form-control" rows="3" placeholder="Tell the user what to fix if status is rejected."><?=e($co['rejection_reason'] ?? '')?></textarea>
                </div>

                <div class="custom-control custom-switch mb-2">
                  <input type="checkbox" class="custom-control-input" id="is_verified" name="is_verified" value="1" <?=(int)($co['is_verified']??0)?'checked':''?>>
                  <label class="custom-control-label" for="is_verified">Verified company badge</label>
                </div>

                <div class="form-group">
                  <label>Verification status</label>
                  <select name="verification_status" class="form-control">
                    <?php foreach(['not_verified'=>'Not Verified','requested'=>'Verification Requested','under_review'=>'Under Review','verified'=>'Verified','rejected'=>'Verification Rejected','expired'=>'Verification Expired'] as $k=>$v): ?>
                      <option value="<?=e($k)?>" <?=($co['verification_status']??'not_verified')===$k?'selected':''?>><?=e($v)?></option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div class="form-group">
                  <label>Verified until</label>
                  <input type="date" name="verification_until" class="form-control" value="<?=e($co['verification_until'] ?? '')?>">
                </div>

                <div class="custom-control custom-switch mb-2">
                  <input type="checkbox" class="custom-control-input" id="is_featured" name="is_featured" value="1" <?=(int)($co['is_featured']??0)?'checked':''?>>
                  <label class="custom-control-label" for="is_featured">Featured company</label>
                </div>

                <div class="custom-control custom-switch mb-3">
                  <input type="checkbox" class="custom-control-input" id="is_sponsored" name="is_sponsored" value="1" <?=(int)($co['is_sponsored']??0)?'checked':''?>>
                  <label class="custom-control-label" for="is_sponsored">Sponsored company</label>
                </div>

                <div class="form-group">
                  <label>Sponsored until</label>
                  <input type="datetime-local" name="sponsored_until" class="form-control" value="<?=!empty($co['sponsored_until'])?e(date('Y-m-d\TH:i', strtotime($co['sponsored_until']))):''?>">
                </div>

                <div class="form-group">
                  <label>Admin notes <small class="text-muted">private</small></label>
                  <textarea name="admin_note" rows="4" class="form-control" placeholder="Private admin note. User cannot see this."><?=e($co['admin_note'] ?? '')?></textarea>
                </div>

                <button class="btn btn-success btn-lg btn-block">
                  <i class="fas fa-save mr-1"></i>Save Company
                </button>
              </div>
            </div>

            <div class="card">
              <div class="card-body">
                <h5>Profile quality</h5>
                <div class="row">
                  <div class="col-6 mb-3">
                    <div class="mini-stat">
                      <div class="text-muted small">Profile score</div>
                      <div class="h4 mb-1"><?=e($profileScore)?>%</div>
                      <div class="progress" style="height:6px;"><div class="progress-bar bg-info" style="width:<?=e($profileScore)?>%"></div></div>
                      <div class="helper-text mt-2"><?=e(mj_company_score_label($profileScore))?></div>
                    </div>
                  </div>
                  <div class="col-6 mb-3">
                    <div class="mini-stat">
                      <div class="text-muted small">Trust score</div>
                      <div class="h4 mb-1"><?=e($trustScore)?>%</div>
                      <div class="progress" style="height:6px;"><div class="progress-bar bg-success" style="width:<?=e($trustScore)?>%"></div></div>
                      <div class="helper-text mt-2">Trust and visibility</div>
                    </div>
                  </div>
                  <div class="col-6">
                    <div class="mini-stat">
                      <div class="text-muted small">Total listings</div>
                      <div class="h4 mb-0"><?=e($listingsCount)?></div>
                    </div>
                  </div>
                  <div class="col-6">
                    <div class="mini-stat">
                      <div class="text-muted small">Active listings</div>
                      <div class="h4 mb-0"><?=e($activeListings)?></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <?php if($timeline): ?>
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title">Timeline</h3>
                </div>
                <div class="card-body small">
                  <?php foreach($timeline as $t): ?>
                    <div class="border-left pl-2 mb-3">
                      <b><?=e($t['action'] ?? $t['action_type'] ?? 'Update')?></b><br>
                      <span class="text-muted"><?=e($t['created_at'] ?? '')?> • <?=e($t['actor_type'] ?? 'system')?></span><br>
                      <?=e($t['note'] ?? $t['action_note'] ?? '')?>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </form>
  </div>
</section>
</div>
<?php include __DIR__.'/_footer.php'; ?>
