<?php
if (!defined('ABSPATH')) exit;

class SIMPINBY_Activator {
    public static function activate() {
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();

        $invoice_table = $wpdb->prefix . "simpinby_invoices";
        $items_table   = $wpdb->prefix . "simpinby_invoice_items";
        $customers     = $wpdb->prefix . "simpinby_customers";
        $products      = $wpdb->prefix . "simpinby_products";

        $sql1 = "CREATE TABLE $customers (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            name VARCHAR(200) NOT NULL,
            phone VARCHAR(50) NULL,
            email VARCHAR(190) NULL,
            address TEXT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY name_idx (name),
            KEY phone_idx (phone)
        ) $charset_collate;";

        $sql2 = "CREATE TABLE $products (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            name VARCHAR(200) NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY name_idx (name)
        ) $charset_collate;";

        $sql3 = "CREATE TABLE $invoice_table (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            invoice_number VARCHAR(50) NOT NULL,
            customer_id BIGINT UNSIGNED NOT NULL,
            status VARCHAR(20) DEFAULT 'unpaid',
            is_archived TINYINT(1) DEFAULT 0,
            tax_name VARCHAR(50) NULL,
            tax_percent DECIMAL(5,2) DEFAULT 0,
            discount DECIMAL(10,2) DEFAULT 0,
            subtotal DECIMAL(10,2) DEFAULT 0,
            total_tax DECIMAL(10,2) DEFAULT 0,
            total_amount DECIMAL(10,2) DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY invoice_number_unique (invoice_number),
            KEY customer_id_idx (customer_id),
            KEY status_idx (status),
            KEY created_at_idx (created_at)
        ) $charset_collate;";

        $sql4 = "CREATE TABLE $items_table (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            invoice_id BIGINT UNSIGNED NOT NULL,
            product_id BIGINT UNSIGNED NULL,
            product_name VARCHAR(200) NOT NULL,
            qty INT DEFAULT 1,
            price DECIMAL(10,2) DEFAULT 0,
            row_total DECIMAL(10,2) DEFAULT 0,
            PRIMARY KEY (id),
            KEY invoice_id_idx (invoice_id)
        ) $charset_collate;";

        dbDelta($sql1);
        dbDelta($sql2);
        dbDelta($sql3);
        dbDelta($sql4);
    }
}
