<?php
require_once __DIR__ . '/../../app/includes/auth.php';
require_auth(); require_role_access('customer:update'); verify_csrf();

$id = (int)post('id');
$stmt = db()->prepare('SELECT * FROM customers WHERE id = ?');
$stmt->execute([$id]);
$c = $stmt->fetch();

if (!$c || (current_user()['role'] !== 'admin' && (int)$c['created_by'] !== current_user()['id'])) {
    http_response_code(403);
    exit('Customer not found or permission denied.');
}

$name = trim((string)post('customer_name'));
if ($name === '') { flash('error', 'Customer name is required.'); redirect('/customers/edit.php?id=' . $id); }
$email = trim((string)post('email'));
$phone = trim((string)post('phone'));
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) { flash('error', 'Please enter a valid customer email.'); redirect('/customers/edit.php?id=' . $id); }
if (strlen($phone) > 60) { flash('error', 'Phone number is too long.'); redirect('/customers/edit.php?id=' . $id); }

$stmt = db()->prepare('UPDATE customers SET customer_name = ?, phone = ?, email = ?, address = ?, location = ?, customer_type = ?, updated_at = ? WHERE id = ?');
$stmt->execute([$name, $phone, $email, post('address'), post('location'), post('customer_type'), now(), $id]);
log_activity('customer.update', 'Updated customer ' . $name);
flash('success', 'Customer updated successfully.');
redirect('/customers/index.php');
