<?php
/**
 * Customer.php - Customer Management Class
 * Handles customer records and contact information
 */

class Customer {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Create new customer record
     */
    public function create($user_id, $first_name, $last_name, $email, $phone = null, $address = null, $city = null, $postcode = null, $customer_type = 'individual') {
        try {
            $stmt = $this->pdo->prepare("
                INSERT INTO customers (user_id, first_name, last_name, email, phone, address, city, postcode, customer_type)
                VALUES (:user_id, :first_name, :last_name, :email, :phone, :address, :city, :postcode, :customer_type)
            ");

            $stmt->execute([
                ':user_id' => $user_id,
                ':first_name' => sanitize_input($first_name),
                ':last_name' => sanitize_input($last_name),
                ':email' => sanitize_input($email),
                ':phone' => sanitize_input($phone),
                ':address' => sanitize_input($address),
                ':city' => sanitize_input($city),
                ':postcode' => sanitize_input($postcode),
                ':customer_type' => $customer_type
            ]);

            return $this->pdo->lastInsertId();
        } catch (Exception $e) {
            log_action(null, null, 'CUSTOMER_CREATE_ERROR', 'Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Get customer by ID
     */
    public function get($customer_id, $user_id = null) {
        try {
            $query = "SELECT * FROM customers WHERE id = :id";
            $params = [':id' => $customer_id];

            if ($user_id) {
                $query .= " AND user_id = :user_id";
                $params[':user_id'] = $user_id;
            }

            $stmt = $this->pdo->prepare($query);
            $stmt->execute($params);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Get customer by email
     */
    public function getByEmail($email, $user_id) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT * FROM customers
                WHERE email = :email AND user_id = :user_id
                LIMIT 1
            ");

            $stmt->execute([
                ':email' => sanitize_input($email),
                ':user_id' => $user_id
            ]);

            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Get all customers for a user
     */
    public function getByUser($user_id, $limit = 50, $offset = 0) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT * FROM customers
                WHERE user_id = :user_id
                ORDER BY created_at DESC
                LIMIT :limit OFFSET :offset
            ");

            $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->execute();

            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Search customers
     */
    public function search($user_id, $search_term) {
        try {
            $term = '%' . sanitize_input($search_term) . '%';

            $stmt = $this->pdo->prepare("
                SELECT * FROM customers
                WHERE user_id = :user_id AND (
                    first_name LIKE :term OR
                    last_name LIKE :term OR
                    email LIKE :term OR
                    phone LIKE :term
                )
                ORDER BY first_name ASC
                LIMIT 50
            ");

            $stmt->execute([
                ':user_id' => $user_id,
                ':term' => $term
            ]);

            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Update customer
     */
    public function update($customer_id, $data) {
        try {
            $allowed_fields = ['first_name', 'last_name', 'email', 'phone', 'address', 'city', 'postcode', 'customer_type'];
            $set_parts = [];
            $params = [':id' => $customer_id];

            foreach ($allowed_fields as $field) {
                if (isset($data[$field])) {
                    $set_parts[] = "$field = :$field";
                    $params[":$field"] = sanitize_input($data[$field]);
                }
            }

            if (empty($set_parts)) {
                return false;
            }

            $query = "UPDATE customers SET " . implode(', ', $set_parts) . " WHERE id = :id";
            $stmt = $this->pdo->prepare($query);

            return $stmt->execute($params);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Get customer count
     */
    public function getCount($user_id) {
        try {
            $stmt = $this->pdo->prepare("SELECT COUNT(*) as count FROM customers WHERE user_id = :user_id");
            $stmt->execute([':user_id' => $user_id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result['count'];
        } catch (Exception $e) {
            return 0;
        }
    }
}
?>
