<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/access_guards.php';
auth_require_login();
$pdo = crm_pdo();
gp_require_staff_access($pdo);
$page_title = 'External partner';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$item = [
    'code' => '',
    'company_name' => '',
    'contact_person' => '',
    'phone' => '',
    'email' => '',
    'specialty' => '',
    'vat_number' => '',
    'city' => '',
    'rate_type' => 'custom',
    'rate_amount' => '',
    'notes' => '',
    'active' => 1,
];

$errors = [];

if ($id) {
    $st = $pdo->prepare("
        SELECT code, company_name, contact_person, phone, email, specialty, vat_number, city, rate_type, rate_amount, notes, active
        FROM external_partners
        WHERE id = :id
        LIMIT 1
    ");
    $st->execute([':id' => $id]);
    $row = $st->fetch();
    if ($row) $item = array_merge($item, $row);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $id = (int)($_POST['id'] ?? 0);
    foreach (array_keys($item) as $k) {
        if ($k === 'active') continue;
        $item[$k] = trim((string)($_POST[$k] ?? ''));
    }
    $item['active'] = isset($_POST['active']) ? 1 : 0;

    if ($item['company_name'] === '') $errors[] = 'Company name is required.';
    if ($item['code'] === '') $item['code'] = 'PART-' . date('Ymd-His');

    if (!$errors) {
        $params = [
            ':code' => $item['code'],
            ':company_name' => $item['company_name'],
            ':contact_person' => $item['contact_person'] !== '' ? $item['contact_person'] : null,
            ':phone' => $item['phone'] !== '' ? $item['phone'] : null,
            ':email' => $item['email'] !== '' ? $item['email'] : null,
            ':specialty' => $item['specialty'] !== '' ? $item['specialty'] : null,
            ':vat_number' => $item['vat_number'] !== '' ? $item['vat_number'] : null,
            ':city' => $item['city'] !== '' ? $item['city'] : null,
            ':rate_type' => $item['rate_type'] !== '' ? $item['rate_type'] : 'custom',
            ':rate_amount' => $item['rate_amount'] !== '' ? $item['rate_amount'] : null,
            ':notes' => $item['notes'] !== '' ? $item['notes'] : null,
            ':active' => $item['active'],
        ];

        if ($id > 0) {
            $sql = "
                UPDATE external_partners
                SET
                    code = :code,
                    company_name = :company_name,
                    contact_person = :contact_person,
                    phone = :phone,
                    email = :email,
                    specialty = :specialty,
                    vat_number = :vat_number,
                    city = :city,
                    rate_type = :rate_type,
                    rate_amount = :rate_amount,
                    notes = :notes,
                    active = :active
                WHERE id = :id
            ";
            $params[':id'] = $id;
        } else {
            $sql = "
                INSERT INTO external_partners
                    (code, company_name, contact_person, phone, email, specialty, vat_number, city, rate_type, rate_amount, notes, active)
                VALUES
                    (:code, :company_name, :contact_person, :phone, :email, :specialty, :vat_number, :city, :rate_type, :rate_amount, :notes, :active)
            ";
        }

        $st = $pdo->prepare($sql);
        $st->execute($params);

        if (!$id) $id = (int)$pdo->lastInsertId();
        redirect('/gopools/public/partners/edit.php?id=' . $id);
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1><?php echo $id ? 'Edit external partner' : 'New external partner'; ?></h1>
  </div>
  <?php if ($id): ?>
    <div class="page-header-actions">
      <a class="btn btn-secondary btn-sm" href="/gopools/public/partners/history.php?id=<?php echo (int)$id; ?>">History</a>
    </div>
  <?php endif; ?>
</div>

<div class="card">
  <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
  <form method="post">
      <?php echo csrf_field(); ?>
    <input type="hidden" name="id" value="<?php echo (int)$id; ?>">
    <div class="form-grid">
      <div class="form-group"><label>Code</label><input name="code" value="<?php echo h($item['code']); ?>"></div>
      <div class="form-group"><label>Company / partner name</label><input name="company_name" value="<?php echo h($item['company_name']); ?>"></div>
      <div class="form-group"><label>Contact person</label><input name="contact_person" value="<?php echo h($item['contact_person']); ?>"></div>
      <div class="form-group"><label>Phone</label><input name="phone" value="<?php echo h($item['phone']); ?>"></div>
      <div class="form-group"><label>Email</label><input name="email" value="<?php echo h($item['email']); ?>"></div>
      <div class="form-group"><label>Specialty</label><input name="specialty" value="<?php echo h($item['specialty']); ?>" placeholder="Electrician / Excavation / Tiles"></div>
      <div class="form-group"><label>VAT number</label><input name="vat_number" value="<?php echo h($item['vat_number']); ?>"></div>
      <div class="form-group"><label>City</label><input name="city" value="<?php echo h($item['city']); ?>"></div>
      <div class="form-group">
        <label>Rate type</label>
        <select name="rate_type">
          <?php foreach (['per_hour','per_day','per_project','custom'] as $rt): ?>
            <option value="<?php echo h($rt); ?>" <?php echo $item['rate_type'] === $rt ? 'selected' : ''; ?>><?php echo h(str_replace('_', ' ', $rt)); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group"><label>Rate amount</label><input type="number" step="0.01" name="rate_amount" value="<?php echo h($item['rate_amount']); ?>"></div>
      <div class="form-group"><label>Active</label><div><input type="checkbox" name="active" <?php echo ((int)$item['active'] === 1) ? 'checked' : ''; ?>></div></div>
      <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"><?php echo h($item['notes']); ?></textarea></div>
    </div>
    <div class="form-actions">
      <button class="btn btn-primary" type="submit">Save</button>
      <a class="btn btn-secondary" href="/gopools/public/partners/index.php">Back</a>
    </div>
  </form>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
