<?php
declare(strict_types=1);

/**
 * modules/payroll/staff/edit.php
 * Create / Edit Staff
 *
 * - Role guard: MD, Accounts, Admin
 * - Fields:
 *    full_name, email, phone, job_title
 *    department (Rent / Chauffeur)
 *    pay_cycle (Monthly / Weekly)
 *    salary_amount, salary_day (monthly) OR salary_weekday (weekly)
 *    start_date, end_date, is_active
 *    address, emergency_contact, notes
 *    bank (bank_name, account_name, account_number, sort_code, iban, swift, bank_notes)
 * - Bank details are saved as JSON (keys: bank_name, account_name, account_number, sort_code, iban, swift, notes)
 * - Redirects back to list on success
 */

require_once dirname(__DIR__, 3) . '/config/functions.php';
require_role(['MD','Accounts','Admin']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$errors = [];
$notice = null;

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

// Load existing record when editing
$row = [
  'full_name'       => '',
  'email'           => '',
  'phone'           => '',
  'job_title'       => '',
  'department'      => 'Chauffeur', // default
  'pay_cycle'       => 'Monthly',
  'salary_amount'   => 0.00,
  'salary_day'      => 28,
  'salary_weekday'  => 5, // Friday
  'start_date'      => '',
  'end_date'        => '',
  'is_active'       => 1,
  'address'         => '',
  'emergency_contact'=> '',
  'notes'           => '',
  'bank_details'    => null,
];

// If editing, fetch
if ($id > 0) {
  try {
    $q = db()->prepare("
      SELECT id, company_id, full_name, email, phone, job_title, department,
             pay_cycle, salary_amount, salary_day, salary_weekday,
             start_date, end_date, is_active,
             address, emergency_contact, notes, bank_details
        FROM staff_members
       WHERE id = :id AND company_id = :cid
       LIMIT 1
    ");
    $q->execute([':id' => $id, ':cid' => $cid]);
    $existing = $q->fetch();
    if (!$existing) {
      $errors[] = 'Staff not found or access denied.';
      $id = 0; // fallback to add-new mode
    } else {
      $row = array_merge($row, $existing);
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to load staff.';
  }
}

// Helper: decode bank JSON for form prefills
$bank = [
  'bank_name'      => '',
  'account_name'   => '',
  'account_number' => '',
  'sort_code'      => '',
  'iban'           => '',
  'swift'          => '',
  'notes'          => '',
];
if (!empty($row['bank_details'])) {
  $bd = json_decode((string)$row['bank_details'], true);
  if (is_array($bd)) {
    foreach ($bank as $k => $v) {
      if (isset($bd[$k])) $bank[$k] = (string)$bd[$k];
    }
  }
}

// Handle POST (create/update)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    // Read & validate
    $full_name   = trim((string)($_POST['full_name'] ?? ''));
    $email       = trim((string)($_POST['email'] ?? ''));
    $phone       = trim((string)($_POST['phone'] ?? ''));
    $job_title   = trim((string)($_POST['job_title'] ?? ''));
    $department  = trim((string)($_POST['department'] ?? 'Chauffeur'));
    $pay_cycle   = trim((string)($_POST['pay_cycle'] ?? 'Monthly'));
    $salary_amt  = to_dec($_POST['salary_amount'] ?? 0);
    $salary_day  = isset($_POST['salary_day']) ? (int)$_POST['salary_day'] : null;
    $salary_wd   = isset($_POST['salary_weekday']) ? (int)$_POST['salary_weekday'] : null;
    $start_date  = trim((string)($_POST['start_date'] ?? ''));
    $end_date    = trim((string)($_POST['end_date'] ?? ''));
    $is_active   = isset($_POST['is_active']) ? 1 : 0;

    $address           = trim((string)($_POST['address'] ?? ''));
    $emergency_contact = trim((string)($_POST['emergency_contact'] ?? ''));
    $notes             = trim((string)($_POST['notes'] ?? ''));

    // Bank fields
    $bank_input = [
      'bank_name'      => trim((string)($_POST['bank_name'] ?? '')),
      'account_name'   => trim((string)($_POST['account_name'] ?? '')),
      'account_number' => trim((string)($_POST['account_number'] ?? '')),
      'sort_code'      => trim((string)($_POST['sort_code'] ?? '')),
      'iban'           => trim((string)($_POST['iban'] ?? '')),
      'swift'          => trim((string)($_POST['swift'] ?? '')),
      'notes'          => trim((string)($_POST['bank_notes'] ?? '')),
    ];
    $bank_json = json_encode($bank_input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    // Basic validation
    if ($full_name === '') $errors[] = 'Full name is required.';
    if (!in_array($department, ['Chauffeur','Rent'], true)) $errors[] = 'Invalid department.';
    if (!in_array($pay_cycle, ['Monthly','Weekly'], true)) $errors[] = 'Invalid pay cycle.';
    if ($salary_amt < 0) $errors[] = 'Salary must be zero or positive.';

    // Normalize date formats (YYYY-MM-DD) if provided
    $dateRegex = '/^\d{4}-\d{2}-\d{2}$/';
    if ($start_date !== '' && !preg_match($dateRegex, $start_date)) $errors[] = 'Start date must be YYYY-MM-DD.';
    if ($end_date   !== '' && !preg_match($dateRegex, $end_date))   $errors[] = 'End date must be YYYY-MM-DD.';

    if ($pay_cycle === 'Monthly') {
      if ($salary_day === null || $salary_day < 1 || $salary_day > 28) $errors[] = 'Monthly pay day must be between 1 and 28.';
      $salary_wd = null;
    } else {
      if ($salary_wd === null || $salary_wd < 0 || $salary_wd > 6) $errors[] = 'Weekly pay weekday must be between 0 (Sun) and 6 (Sat).';
      $salary_day = null;
    }

    if (!$errors) {
      if ($id > 0) {
        // UPDATE
        $sql = "
          UPDATE staff_members SET
            full_name = :full_name,
            email = :email,
            phone = :phone,
            job_title = :job_title,
            department = :department,
            pay_cycle = :pay_cycle,
            salary_amount = :salary_amount,
            salary_day = :salary_day,
            salary_weekday = :salary_weekday,
            start_date = :start_date,
            end_date = :end_date,
            is_active = :is_active,
            address = :address,
            emergency_contact = :emergency_contact,
            notes = :notes,
            bank_details = :bank_details,
            updated_at = NOW()
          WHERE id = :id AND company_id = :cid
          LIMIT 1
        ";
        $stmt = db()->prepare($sql);
        $stmt->execute([
          ':full_name'       => $full_name,
          ':email'           => $email !== '' ? $email : null,
          ':phone'           => $phone !== '' ? $phone : null,
          ':job_title'       => $job_title !== '' ? $job_title : null,
          ':department'      => $department,
          ':pay_cycle'       => $pay_cycle,
          ':salary_amount'   => $salary_amt,
          ':salary_day'      => $salary_day,
          ':salary_weekday'  => $salary_wd,
          ':start_date'      => $start_date !== '' ? $start_date : null,
          ':end_date'        => $end_date   !== '' ? $end_date   : null,
          ':is_active'       => $is_active,
          ':address'         => $address !== '' ? $address : null,
          ':emergency_contact'=> $emergency_contact !== '' ? $emergency_contact : null,
          ':notes'           => $notes !== '' ? $notes : null,
          ':bank_details'    => $bank_json,
          ':id'              => $id,
          ':cid'             => $cid,
        ]);
        audit_log('staff.update','staff',$id, ['name'=>$full_name,'department'=>$department,'pay_cycle'=>$pay_cycle]);
        redirect(url_modules('payroll/staff/list.php') . '?ok=1');
      } else {
        // INSERT
        $sql = "
          INSERT INTO staff_members
            (company_id, full_name, email, phone, job_title, department,
             pay_cycle, salary_amount, salary_day, salary_weekday,
             start_date, end_date, is_active, address, emergency_contact,
             notes, bank_details, created_at, updated_at)
          VALUES
            (:cid, :full_name, :email, :phone, :job_title, :department,
             :pay_cycle, :salary_amount, :salary_day, :salary_weekday,
             :start_date, :end_date, :is_active, :address, :emergency_contact,
             :notes, :bank_details, NOW(), NOW())
        ";
        $stmt = db()->prepare($sql);
        $stmt->execute([
          ':cid'             => $cid,
          ':full_name'       => $full_name,
          ':email'           => $email !== '' ? $email : null,
          ':phone'           => $phone !== '' ? $phone : null,
          ':job_title'       => $job_title !== '' ? $job_title : null,
          ':department'      => $department,
          ':pay_cycle'       => $pay_cycle,
          ':salary_amount'   => $salary_amt,
          ':salary_day'      => $salary_day,
          ':salary_weekday'  => $salary_wd,
          ':start_date'      => $start_date !== '' ? $start_date : null,
          ':end_date'        => $end_date   !== '' ? $end_date   : null,
          ':is_active'       => $is_active,
          ':address'         => $address !== '' ? $address : null,
          ':emergency_contact'=> $emergency_contact !== '' ? $emergency_contact : null,
          ':notes'           => $notes !== '' ? $notes : null,
          ':bank_details'    => $bank_json,
        ]);
        $newId = (int)db()->lastInsertId();
        audit_log('staff.create','staff',$newId, ['name'=>$full_name,'department'=>$department,'pay_cycle'=>$pay_cycle]);
        redirect(url_modules('payroll/staff/list.php') . '?ok=1');
      }
    } else {
      // repopulate row for re-render
      $row = array_merge($row, [
        'full_name'      => $full_name,
        'email'          => $email,
        'phone'          => $phone,
        'job_title'      => $job_title,
        'department'     => $department,
        'pay_cycle'      => $pay_cycle,
        'salary_amount'  => $salary_amt,
        'salary_day'     => $salary_day,
        'salary_weekday' => $salary_wd,
        'start_date'     => $start_date,
        'end_date'       => $end_date,
        'is_active'      => $is_active,
        'address'        => $address,
        'emergency_contact'=>$emergency_contact,
        'notes'          => $notes,
      ]);
      $bank = $bank_input; // keep user entries
    }

  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to save staff.';
  }
}

// Render
include dirname(__DIR__, 3) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0"><?= $id>0 ? 'Edit Staff' : 'Add Staff' ?></h1>
    <div class="text-muted">Maintain staff details, pay settings, and bank info.</div>
  </div>
  <div class="d-flex flex-wrap gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('payroll/staff/list.php')) ?>">← Back to Staff</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
<?php if ($errors): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul></div>
<?php endif; ?>

<form method="post" class="row g-3">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <input type="hidden" name="id" value="<?= (int)$id ?>">

  <!-- Identity -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Identity</h2>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Full Name <span class="text-danger">*</span></label>
            <input class="form-control" name="full_name" required value="<?= e($row['full_name']) ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">Email</label>
            <input type="email" class="form-control" name="email" value="<?= e($row['email'] ?? '') ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">Phone</label>
            <input class="form-control" name="phone" value="<?= e($row['phone'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Job Title</label>
            <input class="form-control" name="job_title" value="<?= e($row['job_title'] ?? '') ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Department <span class="text-danger">*</span></label>
            <select class="form-select" name="department" required>
              <option value="Chauffeur" <?= ($row['department']??'')==='Chauffeur'?'selected':'' ?>>Chauffeur</option>
              <option value="Rent" <?= ($row['department']??'')==='Rent'?'selected':'' ?>>Rent</option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label d-block">Status</label>
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" name="is_active" id="swActive" <?= ((int)$row['is_active']===1)?'checked':'' ?>>
              <label class="form-check-label" for="swActive">Active</label>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Pay Settings -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Pay Settings</h2>
        <div class="row g-3">
          <div class="col-md-3">
            <label class="form-label">Pay Cycle <span class="text-danger">*</span></label>
            <select class="form-select" name="pay_cycle" id="pay_cycle">
              <option value="Monthly" <?= ($row['pay_cycle']??'')==='Monthly'?'selected':'' ?>>Monthly</option>
              <option value="Weekly"  <?= ($row['pay_cycle']??'')==='Weekly'?'selected':'' ?>>Weekly</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">£ Salary / Cycle</label>
            <input type="number" step="0.01" min="0" class="form-control" name="salary_amount" value="<?= e(number_format((float)$row['salary_amount'],2,'.','')) ?>">
          </div>

          <!-- Monthly day -->
          <div class="col-md-3 pc-monthly">
            <label class="form-label">Monthly Pay Day (1–28)</label>
            <input type="number" min="1" max="28" class="form-control" name="salary_day" value="<?= e((string)($row['salary_day'] ?? 28)) ?>">
          </div>

          <!-- Weekly weekday -->
          <div class="col-md-3 pc-weekly">
            <label class="form-label">Weekly Weekday</label>
            <select class="form-select" name="salary_weekday">
              <?php
              $wd = (int)($row['salary_weekday'] ?? 5);
              $days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
              foreach ($days as $i=>$name) {
                $sel = $wd===$i ? 'selected':'';
                echo '<option value="'.(int)$i.'" '.$sel.'>'.e($name).'</option>';
              }
              ?>
            </select>
          </div>

          <div class="col-md-3">
            <label class="form-label">Start Date</label>
            <input type="date" class="form-control" name="start_date" value="<?= e($row['start_date'] ?? '') ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">End Date</label>
            <input type="date" class="form-control" name="end_date" value="<?= e($row['end_date'] ?? '') ?>">
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Contact & Notes -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Contact & Notes</h2>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Address</label>
            <textarea class="form-control" name="address" rows="2"><?= e($row['address'] ?? '') ?></textarea>
          </div>
          <div class="col-md-6">
            <label class="form-label">Emergency Contact</label>
            <textarea class="form-control" name="emergency_contact" rows="2"><?= e($row['emergency_contact'] ?? '') ?></textarea>
          </div>
          <div class="col-12">
            <label class="form-label">Internal Notes</label>
            <textarea class="form-control" name="notes" rows="2"><?= e($row['notes'] ?? '') ?></textarea>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Bank Details -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Bank Details</h2>
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Bank Name</label>
            <input class="form-control" name="bank_name" value="<?= e($bank['bank_name']) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Account Holder</label>
            <input class="form-control" name="account_name" value="<?= e($bank['account_name']) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Account Number</label>
            <input class="form-control" name="account_number" value="<?= e($bank['account_number']) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">Sort Code</label>
            <input class="form-control" name="sort_code" value="<?= e($bank['sort_code']) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">IBAN</label>
            <input class="form-control" name="iban" value="<?= e($bank['iban']) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">SWIFT/BIC</label>
            <input class="form-control" name="swift" value="<?= e($bank['swift']) ?>">
          </div>
          <div class="col-12">
            <label class="form-label">Bank Notes</label>
            <textarea class="form-control" name="bank_notes" rows="2"><?= e($bank['notes']) ?></textarea>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Actions -->
  <div class="col-12 d-flex gap-2">
    <button class="btn btn-dark"><?= $id>0 ? 'Save Changes' : 'Create Staff' ?></button>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('payroll/staff/list.php')) ?>">Cancel</a>
  </div>
</form>

<?php include dirname(__DIR__, 3) . '/includes/footer.php'; ?>

<script>
(function(){
  function togglePayCycle(){
    const cycle = document.getElementById('pay_cycle').value;
    const monthlyEls = document.querySelectorAll('.pc-monthly');
    const weeklyEls  = document.querySelectorAll('.pc-weekly');
    monthlyEls.forEach(el => el.style.display = (cycle === 'Monthly') ? '' : 'none');
    weeklyEls.forEach(el  => el.style.display  = (cycle === 'Weekly')  ? '' : 'none');
  }
  document.getElementById('pay_cycle').addEventListener('change', togglePayCycle);
  togglePayCycle();
})();
</script>
