<?php
require_once __DIR__.'/includes/functions.php';
$u = require_user();
verify_csrf();
mj_company_module_ensure_schema();
mj_user_limits_ensure_schema();
$companyLimitInfo = mj_user_can_add_company((int)$u['id']);

$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');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $companyLimitInfo = mj_user_can_add_company((int)$u['id']);
    if (!$companyLimitInfo['allowed']) {
        flash('error', 'Company limit reached. '.$companyLimitInfo['message'].' Please contact admin to increase your company limit.');
    } else {
    $country = !empty($_POST['country_id']) ? one('SELECT * FROM mj_countries WHERE id=?', [(int)$_POST['country_id']]) : null;
    $data = [
        'user_id' => (int)$u['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'] ?? ($country['timezone_default'] ?? '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' => setting('company_approval_required','1') === '1' ? 'pending' : 'active',
        'is_verified' => 0,
        'is_featured' => 0,
        '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 {
            $data['slug'] = mj_slug_unique('mj_companies', $data['name']);
            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'); }
            $insert = mj_company_filter_columns_fresh('mj_companies', $data);
            $cols = array_keys($insert);
            $placeholders = array_fill(0, count($cols), '?');
            q('INSERT INTO mj_companies(`'.implode('`,`', $cols).'`,created_at,updated_at) VALUES('.implode(',', $placeholders).',NOW(),NOW())', array_values($insert));
            $id = (int)db()->lastInsertId();
            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, 'user', (int)$u['id'], 'user_create', 'Company profile submitted. Services saved: '.$serviceCount, '', (string)$data['status']);
            if ($data['status'] === 'pending') { flash('success', 'Company profile submitted. Our team will review it and notify you once it is published.'); }
            else { flash('success', 'Company profile created successfully.'); }
            redirect('my-companies.php');
        } catch (Throwable $e) {
            flash('error', $e->getMessage());
        }
    }
}
}
$pageTitle = 'Add 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">Add Company Profile</h1><p class="text-muted mb-0">Create a company profile so buyers can trust your business and contact you easily.</p></div>
        <a href="<?=base_url('my-companies.php')?>" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>My Companies</a>
      </div>
      <div class="mj-card p-4 mb-4">
        <h3 class="fw-bold">How to create a strong company profile</h3>
        <div class="row g-3 mt-1">
          <div class="col-md-3"><div class="border rounded-4 p-3 h-100"><b>1. Add details</b><br><small class="text-muted">Company name, category and location.</small></div></div>
          <div class="col-md-3"><div class="border rounded-4 p-3 h-100"><b>2. Add contact</b><br><small class="text-muted">Phone, WhatsApp, email or website.</small></div></div>
          <div class="col-md-3"><div class="border rounded-4 p-3 h-100"><b>3. Add services</b><br><small class="text-muted">Tell customers what you offer.</small></div></div>
          <div class="col-md-3"><div class="border rounded-4 p-3 h-100"><b>4. Submit</b><br><small class="text-muted">Admin reviews before public approval.</small></div></div>
        </div>
      </div>
      <div class="mj-card p-3 mb-4">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
          <div>
            <h5 class="fw-bold mb-1"><i class="bi bi-building me-1"></i>Your company limit</h5>
            <p class="text-muted mb-0 small"><?=e($companyLimitInfo['message'])?></p>
          </div>
          <?php if(!$companyLimitInfo['allowed']): ?><span class="mj-badge warn">Limit reached</span><?php else: ?><span class="mj-badge good">Available</span><?php endif; ?>
        </div>
      </div>

      <?php if(!$companyLimitInfo['allowed']): ?>
        <div class="mj-card p-5 text-center">
          <div class="mj-icon-box mx-auto mb-3"><i class="bi bi-lock"></i></div>
          <h3 class="fw-bold">Company limit reached</h3>
          <p class="text-muted">You cannot add more company profiles right now. Please contact admin if you need more company slots.</p>
          <?php if(mj_user_feature_enabled('extra_company_slots',(int)$u['id'])): ?><a class="btn btn-primary rounded-pill" href="<?=e(base_url('request-more-slots.php?type=company'))?>">Request More Company Slots</a><?php else: ?><span class="btn btn-outline-secondary rounded-pill disabled">Extra Slots Disabled</span><?php endif; ?> <a class="btn btn-outline-primary rounded-pill" href="<?=e(base_url('my-companies.php'))?>">View My Companies</a>
        </div>
      <?php else: ?>
      <form method="post" enctype="multipart/form-data" class="mj-card p-4">
        <?=csrf_input()?>
        <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 class="form-control" name="name" maxlength="220" required value="<?=e($_POST['name'] ?? '')?>" placeholder="Example: MJ Data Recovery Singapore"></div>
          <div class="col-md-4"><label class="form-label">Registration no.</label><input class="form-control" name="registration_no" maxlength="120" value="<?=e($_POST['registration_no'] ?? '')?>" placeholder="Optional"></div>
          <div class="col-md-4"><label class="form-label">Country <span class="text-danger">*</span></label><select class="form-control" name="country_id" onchange="loadStates(this.value,'state_id')" required><option value="">Select country</option><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>" <?=((string)($_POST['country_id'] ?? '')===(string)$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 class="form-control" name="category_id" required><option value="">Select category</option><?php foreach($cats as $cat): ?><option value="<?=e($cat['id'])?>" <?=((string)($_POST['category_id'] ?? '')===(string)$cat['id'])?'selected':''?>><?=e($cat['name'])?></option><?php endforeach; ?></select></div>
          <div class="col-md-4"><label class="form-label">Timezone</label><input class="form-control" name="timezone" value="<?=e($_POST['timezone'] ?? '')?>" placeholder="Auto from country if empty"></div>
          <div class="col-md-6"><label class="form-label">State</label><select class="form-control" name="state_id" id="state_id" onchange="loadCities(this.value,'city_id')"><option value="">State</option></select></div>
          <div class="col-md-6"><label class="form-label">City</label><select class="form-control" name="city_id" id="city_id"><option value="">City</option></select></div>
          <div class="col-12"><label class="form-label">Business address <span class="text-danger">*</span></label><textarea class="form-control" name="address" rows="3" required placeholder="Full business address or service area"><?=e($_POST['address'] ?? '')?></textarea></div>
          <div class="col-md-6"><label class="form-label">Latitude <small class="text-muted">optional</small></label><input class="form-control" name="latitude" value="<?=e($_POST['latitude'] ?? '')?>"></div>
          <div class="col-md-6"><label class="form-label">Longitude <small class="text-muted">optional</small></label><input class="form-control" name="longitude" value="<?=e($_POST['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 class="form-control" name="phone" maxlength="80" value="<?=e($_POST['phone'] ?? '')?>"></div>
          <div class="col-md-4"><label class="form-label">WhatsApp</label><input class="form-control" name="whatsapp" maxlength="80" value="<?=e($_POST['whatsapp'] ?? '')?>"></div>
          <div class="col-md-4"><label class="form-label">Email</label><input class="form-control" type="email" name="email" maxlength="190" value="<?=e($_POST['email'] ?? '')?>"></div>
          <div class="col-12"><label class="form-label">Website</label><input class="form-control" name="website" placeholder="https://example.com" value="<?=e($_POST['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 class="form-control" name="description" rows="6" required minlength="20" placeholder="Describe your company, services, areas covered and why customers should contact you."><?=e($_POST['description'] ?? '')?></textarea>
        <label class="form-label mt-3">Services offered</label><textarea class="form-control" name="services_text" rows="5" placeholder="One service per line&#10;Example: Data Recovery&#10;SSD Recovery&#10;NAS Recovery"><?=e($_POST['services_text'] ?? '')?></textarea>
        <div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label">Logo</label><input class="form-control" type="file" name="logo" accept="image/*"><div class="form-text">JPG, PNG, WEBP or GIF. Max 8MB.</div></div><div class="col-md-6"><label class="form-label">Banner image</label><input class="form-control" type="file" name="cover_image" accept="image/*"><div class="form-text">A wide banner makes the public profile look better.</div></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="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="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="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="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="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="13:00"></div><div class="col-md-3 d-flex align-items-end"><label class="mb-2"><input type="checkbox" name="saturday_closed"> Saturday closed</label></div><div class="col-md-3 d-flex align-items-end"><label class="mb-2"><input type="checkbox" name="sunday_closed" checked> Sunday closed</label></div></div>
        <div class="alert alert-light border rounded-4 mt-4"><i class="bi bi-shield-check me-1"></i> After submission, your company profile may be reviewed before it appears publicly.</div>
        <button class="btn btn-primary btn-lg"><i class="bi bi-send me-1"></i>Submit Company Profile</button>
      </form>
      <?php endif; ?>
    </div>
  </div>
</div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
