<?php
require_once __DIR__ . '/lib/functions.php';
mdw_require_login();

global $mdw_clients_file;
$file = $mdw_clients_file ?? mdw_data_file('clients.json');
$clients = mdw_read_json($file, []);
$editId = $_GET['id'] ?? '';
$edit = null;
foreach ($clients as $c) if (($c['id'] ?? '') === $editId) { $edit = $c; break; }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    if ($action === 'delete') {
        $id = $_POST['id'] ?? '';
        $clients = array_values(array_filter($clients, fn($c) => ($c['id'] ?? '') !== $id));
        mdw_write_json($file, $clients) ? mdw_flash('Client deleted.') : mdw_flash('Could not delete client. Check data permissions.', 'error');
        header('Location: clients.php'); exit;
    }
    $id = $_POST['id'] ?: ('client-' . date('Ymd-His') . '-' . substr(md5((string)mt_rand()), 0, 6));
    $new = [
        'id' => $id,
        'client_name' => trim((string)($_POST['client_name'] ?? '')),
        'business_name' => trim((string)($_POST['business_name'] ?? '')),
        'email' => trim((string)($_POST['email'] ?? '')),
        'phone' => trim((string)($_POST['phone'] ?? '')),
        'website' => trim((string)($_POST['website'] ?? '')),
        'domain' => trim((string)($_POST['domain'] ?? '')),
        'hosting_provider' => trim((string)($_POST['hosting_provider'] ?? '')),
        'status' => trim((string)($_POST['status'] ?? 'Lead')),
        'notes' => trim((string)($_POST['notes'] ?? '')),
        'created_at' => $edit['created_at'] ?? date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
    ];
    $found = false;
    foreach ($clients as $idx => $c) if (($c['id'] ?? '') === $id) { $clients[$idx] = $new; $found = true; break; }
    if (!$found) $clients[] = $new;
    mdw_write_json($file, $clients) ? mdw_flash('Client saved.') : mdw_flash('Could not save client. Check data permissions.', 'error');
    header('Location: clients.php'); exit;
}

mdw_render_header('Clients');
?>
<section class="panel">
  <h2><?php echo $edit ? 'Edit Client' : 'Add Client'; ?></h2>
  <p class="muted">Track client/contact details, hosting notes, domains, and project status. This stays separate from ECT.</p>
  <form method="post">
    <input type="hidden" name="id" value="<?php echo mdw_h($edit['id'] ?? ''); ?>">
    <div class="split">
      <div><label>Client Name</label><input name="client_name" value="<?php echo mdw_h($edit['client_name'] ?? ''); ?>"></div>
      <div><label>Business Name</label><input name="business_name" value="<?php echo mdw_h($edit['business_name'] ?? ''); ?>"></div>
      <div><label>Email</label><input name="email" value="<?php echo mdw_h($edit['email'] ?? ''); ?>"></div>
      <div><label>Phone</label><input name="phone" value="<?php echo mdw_h($edit['phone'] ?? ''); ?>"></div>
      <div><label>Website</label><input name="website" value="<?php echo mdw_h($edit['website'] ?? ''); ?>"></div>
      <div><label>Domain</label><input name="domain" value="<?php echo mdw_h($edit['domain'] ?? ''); ?>"></div>
      <div><label>Hosting Provider</label><input name="hosting_provider" value="<?php echo mdw_h($edit['hosting_provider'] ?? ''); ?>"></div>
      <div><label>Status</label><select name="status"><?php foreach(['Lead','Quoted','Active','Completed','On Hold'] as $s): ?><option <?php echo (($edit['status'] ?? 'Lead')===$s)?'selected':''; ?>><?php echo mdw_h($s); ?></option><?php endforeach; ?></select></div>
    </div>
    <label>Notes</label><textarea name="notes"><?php echo mdw_h($edit['notes'] ?? ''); ?></textarea>
    <p class="row-actions" style="margin-top:18px"><button class="button" type="submit">Save Client</button><?php if($edit): ?><a class="button ghost" href="clients.php">Cancel Edit</a><?php endif; ?></p>
  </form>
</section>

<section class="panel" style="margin-top:20px">
  <h2>Client List</h2>
  <?php if (!$clients): ?><p class="muted">No clients yet.</p><?php else: ?>
  <table><thead><tr><th>Client</th><th>Contact</th><th>Hosting / Domain</th><th>Status</th><th>Actions</th></tr></thead><tbody>
  <?php foreach ($clients as $client): ?>
    <tr>
      <td><strong><?php echo mdw_h($client['business_name'] ?: ($client['client_name'] ?? 'Unnamed')); ?></strong><br><span class="muted"><?php echo mdw_h($client['client_name'] ?? ''); ?></span></td>
      <td><?php echo mdw_h($client['email'] ?? ''); ?><br><?php echo mdw_h($client['phone'] ?? ''); ?></td>
      <td><?php echo mdw_h($client['hosting_provider'] ?? ''); ?><br><span class="muted"><?php echo mdw_h($client['domain'] ?? ''); ?></span></td>
      <td><span class="status <?php echo mdw_h(str_replace(' ', '', $client['status'] ?? 'Lead')); ?>"><?php echo mdw_h($client['status'] ?? 'Lead'); ?></span></td>
      <td class="row-actions"><a class="button ghost" href="clients.php?id=<?php echo urlencode($client['id'] ?? ''); ?>">Edit</a><a class="button" href="document-edit.php?client=<?php echo urlencode($client['id'] ?? ''); ?>">New Document</a><form method="post" onsubmit="return confirm('Delete this client?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?php echo mdw_h($client['id'] ?? ''); ?>"><button class="button danger" type="submit">Delete</button></form></td>
    </tr>
  <?php endforeach; ?>
  </tbody></table>
  <?php endif; ?>
</section>
<?php mdw_render_footer(); ?>
