package models

import (
	"database/sql"
	"time"
)

type Customer struct {
	ID        int
	Name      string
	Email     string
	Phone     string
	Address   string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func CustomerGetAll(db *sql.DB, search string) ([]Customer, error) {
	query := "SELECT id, name, email, phone, address, created_at, updated_at FROM customers"
	args := []interface{}{}
	if search != "" {
		query += " WHERE name LIKE ? OR email LIKE ?"
		s := "%" + search + "%"
		args = append(args, s, s)
	}
	query += " ORDER BY name"

	rows, err := db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var customers []Customer
	for rows.Next() {
		var c Customer
		if err := rows.Scan(&c.ID, &c.Name, &c.Email, &c.Phone, &c.Address, &c.CreatedAt, &c.UpdatedAt); err != nil {
			return nil, err
		}
		customers = append(customers, c)
	}
	return customers, nil
}

func CustomerGetByID(db *sql.DB, id int) (*Customer, error) {
	c := &Customer{}
	err := db.QueryRow(
		"SELECT id, name, email, phone, address, created_at, updated_at FROM customers WHERE id = ?", id,
	).Scan(&c.ID, &c.Name, &c.Email, &c.Phone, &c.Address, &c.CreatedAt, &c.UpdatedAt)
	if err != nil {
		return nil, err
	}
	return c, nil
}

func CustomerInsert(db *sql.DB, c *Customer) error {
	result, err := db.Exec(
		"INSERT INTO customers (name, email, phone, address) VALUES (?, ?, ?, ?)",
		c.Name, c.Email, c.Phone, c.Address,
	)
	if err != nil {
		return err
	}
	id, _ := result.LastInsertId()
	c.ID = int(id)
	return nil
}

func CustomerUpdate(db *sql.DB, c *Customer) error {
	_, err := db.Exec(
		"UPDATE customers SET name = ?, email = ?, phone = ?, address = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
		c.Name, c.Email, c.Phone, c.Address, c.ID,
	)
	return err
}

func CustomerDelete(db *sql.DB, id int) error {
	_, err := db.Exec("DELETE FROM customers WHERE id = ?", id)
	return err
}

func CustomerCount(db *sql.DB) int {
	var count int
	db.QueryRow("SELECT COUNT(*) FROM customers").Scan(&count)
	return count
}
