from datetime import datetime
from database import get_connection, is_postgres

class Clients:
    def __init__(self):
        # Parameter style: Postgres uses %s, SQLite uses ?
        self.ph = "%s" if is_postgres() else "?"

    def client_to_dict(self, row):
        return {
            "id": row[0],
            "user_id": row[1],
            "name": row[2],
            "address": row[3],
            "register_number": row[4],
            "contact_person": row[5],
            "phone": row[6],
            "email": row[7],
            "vat":row[8],
            "created_at": row[9],
        }
    
    def create(self, user_id, name, address, register_number, contact_person, phone=None, email=None, vat=None):
        created_at = datetime.now().isoformat()
        with get_connection() as conn:
            cur = conn.cursor()
            cur.execute(
                f"""
                INSERT INTO clients (user_id, name, address, register_number, contact_person, phone, email, vat, created_at)
                VALUES ({self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph}, {self.ph})
                """,
                (user_id, name, address, register_number, contact_person, phone, email, vat, created_at),
            )
            if hasattr(conn, "commit"):
                conn.commit()

    def get_all_by_user(self, user_id):
        with get_connection() as conn:
            cur = conn.cursor()
            cur.execute(
                f"SELECT * FROM clients WHERE user_id = {self.ph}",
                (user_id,),
            )
            return [self.client_to_dict(row) for row in cur.fetchall()]

    def get_by_id(self, client_id):
        with get_connection() as conn:
            cur = conn.cursor()
            cur.execute(
                f"SELECT * FROM clients WHERE id = {self.ph}",
                (client_id,),
            )
            row = cur.fetchone()
        return self.client_to_dict(row) if row else None

    def update(self, client_id, name, address, register_number, contact_person, phone=None, email=None, vat = None):
        with get_connection() as conn:
            cur = conn.cursor()
            cur.execute(
                f"""
                UPDATE clients
                SET name={self.ph}, address={self.ph}, register_number={self.ph}, contact_person={self.ph},
                    phone={self.ph}, email={self.ph}, vat={self.ph}
                WHERE id={self.ph}
                """,
                (name, address, register_number, contact_person, phone, email, vat, client_id),
            )
            if hasattr(conn, "commit"):
                conn.commit()

    def delete(self, client_id):
        with get_connection() as conn:
            cur = conn.cursor()
            cur.execute(
                f"DELETE FROM clients WHERE id={self.ph}",
                (client_id,),
            )
            if hasattr(conn, "commit"):
                conn.commit()
