<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
verify_csrf();
mj_company_module_ensure_schema();

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$co = $id > 0 ? one('SELECT * FROM mj_companies WHERE id=? AND user_id=? LIMIT 1', [$id, (int)$u['id']]) : null;
if (!$co) { flash('error', 'Company not found or you do not have permission to edit it.'); redirect('my-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');
$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) ?: [];
$pendingRevision = function_exists('mj_review_pending') ? mj_review_pending('company', $id) : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $oldStatus = (string)($co['status'] ?? '');
    $newStatus = setting('company_approval_required','1') === '1' ? 'pending' : 'active';
    $data = [
        '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' => $newStatus,
        'rejection_reason' => null,
        'submitted_at' => date('Y-m-d H:i:s'),
    ];
    $errors = mj_company_validate_data($data);
    if ($errors) {
        foreach ($errors as $err) { flash('error', $err); }
    } else {
        try {
            if (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'); }
            $branchPayload = [
                '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']),
            ];
            $serviceTextPost = (string)($_POST['services_text'] ?? '');

            if (function_exists('mj_review_live_update_required') && mj_review_live_update_required('company', (string)($co['status'] ?? ''))) {
                $reviewData = $data;
                $reviewData['status'] = (string)($co['status'] ?? 'active');
                $reviewData['rejection_reason'] = null;
                $reviewData = mj_company_filter_columns_fresh('mj_companies', $reviewData);
                $rid = mj_review_submit('company', $id, (int)$u['id'], $co, $reviewData, ['branch_data'=>$mainBranch ?: [], 'services_text'=>$serviceText], ['branch_data'=>$branchPayload, 'services_text'=>$serviceTextPost]);
                if (function_exists('mj_company_timeline_add')) { mj_company_timeline_add($id, 'user', (int)$u['id'], 'revision_submitted', 'Company update submitted for admin approval. Revision #'.$rid, (string)($co['status'] ?? ''), (string)($co['status'] ?? '')); }
                if (function_exists('mj_review_admin_alert')) { mj_review_admin_alert('company', $id, 'User submitted company profile changes for: '.$data['name']); }
                if (function_exists('mj263_notify')) { mj263_notify((int)$u['id'], null, 'company_revision_submitted', 'Company update sent for review', 'Your current company profile remains live until admin approves the changes.', 'my-companies.php', 'normal', true); }
                flash('success', 'Your company changes were submitted for admin review. The current public company profile remains live until approval.');
                redirect('my-companies.php');
            }

            $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=? AND user_id=?', array_merge($params, [(int)$u['id']]));
            mj_company_update_main_branch($id, array_merge($data, $branchPayload));
            $serviceCount = mj_company_save_services_from_text($id, $serviceTextPost);
            mj_company_update_scores($id);
            mj_company_timeline_add($id, 'user', (int)$u['id'], 'user_update', 'Company profile updated by owner. Services saved: '.$serviceCount, $oldStatus, $newStatus);
            if ($newStatus === 'pending') { flash('success', 'Your company profile has been updated and is now under review. We will notify you once it is approved.'); }
            else { flash('success', 'Your company profile has been updated successfully.'); }
            redirect('my-companies.php');
        } catch (Throwable $e) {
            flash('error', $e->getMessage());
        }
    }
    $co = one('SELECT * FROM mj_companies WHERE id=? AND user_id=? LIMIT 1', [$id, (int)$u['id']]);
    $serviceText = (string)($_POST['services_text'] ?? $serviceText);
}

$serviceCount = safe_count('SELECT COUNT(*) c FROM mj_company_services WHERE company_id=?', [$id]);
$profileScore = mj_company_profile_score($co, $serviceCount);
$trustScore = mj_company_trust_score($co, $serviceCount);
$pageTitle = 'Edit Company';
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-3 gap-2">
        <div><h1 class="mb-1">Edit Company Profile</h1><p class="text-muted mb-0">Keep your company details clear, complete and easy for customers to understand.</p></div>
        <div><a class="btn btn-outline-secondary" href="<?=base_url('my-companies.php')?>"><i class="bi bi-arrow-left me-1"></i>My Companies</a> <a class="btn btn-outline-primary" target="_blank" href="<?=e(mj_company_public_url($co))?>"><i class="bi bi-eye me-1"></i>View Public</a></div>
      </div>
      <?php if(($co['status'] ?? '') === 'rejected'): ?><div class="alert alert-warning rounded-4"><b>Your company profile needs update.</b><br><?=e($co['rejection_reason'] ?: 'Please review the details and submit again.')?></div><?php endif; ?>
      <?php if(($co['status'] ?? '') === 'pending'): ?><div class="alert alert-info rounded-4"><b>Pending review.</b> Your company is waiting for admin approval. You can still edit and improve the profile.</div><?php endif; ?>
      <?php if($pendingRevision): ?><div class="alert alert-warning rounded-4"><b>Pending update review.</b> Your latest changes are waiting for admin approval. The current public company profile remains live.</div><?php endif; ?>
      <div class="row g-3 mb-4">
        <div class="col-md-6"><div class="mj-card p-3"><div class="d-flex justify-content-between"><b>Profile completeness</b><span><?=e($profileScore)?>%</span></div><div class="progress mt-2" style="height:8px"><div class="progress-bar" style="width:<?=e($profileScore)?>%"></div></div><small class="text-muted">Add logo, services, contact details and description to improve.</small></div></div>
        <div class="col-md-6"><div class="mj-card p-3"><div class="d-flex justify-content-between"><b>Trust score</b><span><?=e($trustScore)?>%</span></div><div class="progress mt-2" style="height:8px"><div class="progress-bar bg-success" style="width:<?=e($trustScore)?>%"></div></div><small class="text-muted">Verification and complete contact details increase trust.</small></div></div>
      </div>
      <form method="post" enctype="multipart/form-data" class="mj-card p-4">
        <?=csrf_input()?><input type="hidden" name="id" value="<?=e($id)?>">
        <h3 class="fw-bold mb-3">Company information</h3>
        <div class="row g-3">
          <div class="col-md-8"><label class="form-label">Company name <span class="text-danger">*</span></label><input name="name" class="form-control" required maxlength="220" value="<?=e($co['name'] ?? '')?>"></div>
          <div class="col-md-4"><label class="form-label">Registration no.</label><input name="registration_no" class="form-control" maxlength="120" value="<?=e($co['registration_no'] ?? '')?>"></div>
          <div class="col-md-4"><label class="form-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'])?>" <?=((int)$co['country_id']===(int)$c['id'])?'selected':''?>><?=e($c['flag_emoji'].' '.$c['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-4"><label class="form-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 class="col-md-4"><label class="form-label">Timezone</label><input name="timezone" class="form-control" maxlength="80" value="<?=e($co['timezone'] ?? 'UTC')?>"></div>
          <div class="col-md-6"><label class="form-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="col-md-6"><label class="form-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="col-12"><label class="form-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="col-md-6"><label class="form-label">Latitude <small class="text-muted">optional</small></label><input name="latitude" class="form-control" value="<?=e($co['latitude'] ?? '')?>"></div>
          <div class="col-md-6"><label class="form-label">Longitude <small class="text-muted">optional</small></label><input name="longitude" class="form-control" value="<?=e($co['longitude'] ?? '')?>"></div>
        </div>
        <hr class="my-4"><h3 class="fw-bold mb-3">Contact details</h3>
        <div class="row g-3">
          <div class="col-md-4"><label class="form-label">Phone</label><input name="phone" class="form-control" maxlength="80" value="<?=e($co['phone'] ?? '')?>"></div>
          <div class="col-md-4"><label class="form-label">WhatsApp</label><input name="whatsapp" class="form-control" maxlength="80" value="<?=e($co['whatsapp'] ?? '')?>"></div>
          <div class="col-md-4"><label class="form-label">Email</label><input type="email" name="email" class="form-control" maxlength="190" value="<?=e($co['email'] ?? '')?>"></div>
          <div class="col-12"><label class="form-label">Website</label><input name="website" class="form-control" placeholder="https://example.com" value="<?=e($co['website'] ?? '')?>"><div class="form-text">At least one contact option is required: phone, WhatsApp or email.</div></div>
        </div>
        <hr class="my-4"><h3 class="fw-bold mb-3">Profile content</h3>
        <label class="form-label">Description <span class="text-danger">*</span></label><textarea name="description" rows="6" class="form-control" required minlength="20" placeholder="Tell customers what you offer, service area, experience and how to contact you."><?=e($co['description'] ?? '')?></textarea>
        <label class="form-label mt-3">Services offered</label><textarea name="services_text" rows="5" class="form-control" placeholder="One service per line&#10;Example: Data Recovery&#10;SSD Recovery&#10;NAS Recovery"><?=e($serviceText)?></textarea>
        <div class="row g-3 mt-1"><div class="col-md-6"><label class="form-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:90px" alt="Logo"><?php endif; ?></div><div class="col-md-6"><label class="form-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:90px" alt="Banner"><?php endif; ?></div></div>
        <hr class="my-4"><h3 class="fw-bold mb-3">Opening hours</h3>
        <div class="row g-3">
          <div class="col-md-3"><label class="form-label">Weekday open</label><input type="time" name="weekday_open" class="form-control" value="<?=e($hours['mon']['open'] ?? '09:00')?>"></div>
          <div class="col-md-3"><label class="form-label">Weekday close</label><input type="time" name="weekday_close" class="form-control" value="<?=e($hours['mon']['close'] ?? '18:00')?>"></div>
          <div class="col-md-3"><label class="form-label">Saturday open</label><input type="time" name="saturday_open" class="form-control" value="<?=e($hours['sat']['open'] ?? '09:00')?>"></div>
          <div class="col-md-3"><label class="form-label">Saturday close</label><input type="time" name="saturday_close" class="form-control" value="<?=e($hours['sat']['close'] ?? '13:00')?>"></div>
          <div class="col-md-3"><label class="form-label">Sunday open</label><input type="time" name="sunday_open" class="form-control" value="<?=e($hours['sun']['open'] ?? '09:00')?>"></div>
          <div class="col-md-3"><label class="form-label">Sunday close</label><input type="time" name="sunday_close" class="form-control" value="<?=e($hours['sun']['close'] ?? '13:00')?>"></div>
          <div class="col-md-3 d-flex align-items-end"><label class="mb-2"><input type="checkbox" name="saturday_closed" <?=!empty($hours['sat']['closed'])?'checked':''?>> Saturday closed</label></div>
          <div class="col-md-3 d-flex align-items-end"><label class="mb-2"><input type="checkbox" name="sunday_closed" <?=!empty($hours['sun']['closed'])?'checked':''?>> Sunday closed</label></div>
        </div>
        <div class="alert alert-light border rounded-4 mt-4"><i class="bi bi-lightbulb me-1"></i> Tip: Companies with clear description, logo, WhatsApp and services usually get more enquiries.</div>
        <button class="btn btn-primary btn-lg"><i class="bi bi-save me-1"></i>Save Company Profile</button>
      </form>
    </div>
  </div>
</div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
