<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: clients.php');
    exit;
}

$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT id FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];

$id = $_POST['id'] ?? '';
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$address = trim($_POST['address'] ?? '');
$city = trim($_POST['city'] ?? '');
$state = trim($_POST['state'] ?? '');
$postal_code = trim($_POST['postal_code'] ?? '');
$country = trim($_POST['country'] ?? '');
$notes = trim($_POST['notes'] ?? '');

if (empty($name)) {
    $_SESSION['error'] = 'Client name is required.';
    header('Location: clients.php');
    exit;
}

if ($id) {
    $stmt = $pdo->prepare("UPDATE clients SET name=?, email=?, phone=?, address=?, city=?, state=?, postal_code=?, country=?, notes=? WHERE id=? AND company_id=?");
    $stmt->execute([$name, $email, $phone, $address, $city, $state, $postal_code, $country, $notes, $id, $companyId]);
    header('Location: clients.php?msg=updated');
} else {
    $stmt = $pdo->prepare("INSERT INTO clients (company_id, name, email, phone, address, city, state, postal_code, country, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$companyId, $name, $email, $phone, $address, $city, $state, $postal_code, $country, $notes]);
    header('Location: clients.php?msg=added');
}
?>