<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();
$authUser = require_user();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    [$page, $perPage, $offset] = paginate_params();
    $search = clean_str($_GET['search'] ?? '');
    $group = clean_str($_GET['group'] ?? '');

    $where = ['user_email = :email'];
    $params = [':email' => $authUser['email']];
    if ($search !== '') { $where[] = '(name LIKE :search OR phone_number LIKE :search2)'; $params[':search'] = "%$search%"; $params[':search2'] = "%$search%"; }
    if ($group !== '') { $where[] = 'group_name = :group'; $params[':group'] = $group; }
    $whereSql = implode(' AND ', $where);

    $count = $pdo->prepare("SELECT COUNT(*) FROM contacts WHERE $whereSql");
    $count->execute($params);
    $total = (int) $count->fetchColumn();

    $stmt = $pdo->prepare("SELECT * FROM contacts WHERE $whereSql ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    send_success([
        'contacts' => $stmt->fetchAll(),
        'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
    ]);
}

if ($method === 'POST') {
    $input = get_json_input();
    require_fields($input, ['name', 'phone_number']);

    $stmt = $pdo->prepare(
        'INSERT INTO contacts (user_email, name, phone_number, whatsapp_number, email, company, tags, notes, group_name)
         VALUES (:email, :name, :phone, :wa, :contact_email, :company, :tags, :notes, :group_name)'
    );
    $stmt->execute([
        ':email'         => $authUser['email'],
        ':name'          => clean_str($input['name']),
        ':phone'         => clean_str($input['phone_number']),
        ':wa'            => clean_str($input['whatsapp_number'] ?? ''),
        ':contact_email' => clean_str($input['email'] ?? ''),
        ':company'       => clean_str($input['company'] ?? ''),
        ':tags'          => clean_str($input['tags'] ?? 'Lead'),
        ':notes'         => clean_str($input['notes'] ?? ''),
        ':group_name'    => clean_str($input['group_name'] ?? 'Default'),
    ]);

    send_success(['id' => (int) $pdo->lastInsertId()], 'Contact added.', 201);
}

if ($_SERVER['REQUEST_METHOD'] === 'PUT' && isset($_GET['id'])) {
    $input = get_json_input();
    $allowed = ['name', 'phone_number', 'whatsapp_number', 'email', 'company', 'tags', 'notes', 'group_name', 'status'];
    $fields = [];
    $params = [':id' => (int) $_GET['id'], ':email' => $authUser['email']];
    foreach ($allowed as $f) {
        if (isset($input[$f])) { $fields[] = "$f = :$f"; $params[":$f"] = clean_str($input[$f]); }
    }
    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE contacts SET ' . implode(', ', $fields) . ' WHERE id = :id AND user_email = :email');
    $stmt->execute($params);
    send_success(null, 'Contact updated.');
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('DELETE FROM contacts WHERE id = :id AND user_email = :email');
    $stmt->execute([':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    send_success(null, 'Contact deleted.');
}

send_error('Invalid request.', 400);
