<?php

/**
 * Class Clicks
 *
 * Represents the Clicks Model.
 *
 * @package LinkFiliate\Models
 * @since 1.0.0
 */

namespace LinkFiliate\App\Models;

if (! defined('ABSPATH')) {
    exit;
}

class Clicks
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table;

    /**
     * Constructor untuk set $wpdb dan table name
     */
    public function __construct()
    {
        global $wpdb;
        $this->table = $wpdb->prefix . LINKFILIATE_DB_BASE . '_clicks';
    }

    /**
     * Get all campaigns.
     *
     * @return array|null
     */

    public function get_all()
    {
        global $wpdb;

        $clicks_table    = $wpdb->prefix . LINKFILIATE_DB_BASE . '_clicks';     // alias: c
        $campaigns_table = $wpdb->prefix . LINKFILIATE_DB_BASE . '_campaigns';  // alias: cp

        $query = $wpdb->prepare(
            "SELECT 
        c.*, 
        cp.name AS campaign_name
    FROM %i AS c
    LEFT JOIN %i AS cp ON c.campaign_id = cp.id
    ORDER BY c.created_at DESC
    LIMIT 50",
            $clicks_table,
            $campaigns_table
        );

        $results = $wpdb->get_results($query, ARRAY_A); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        return $results;
    }




    /**
     * Get single click by ID
     *
     * @param int $id
     * @return array|null
     */
    public function find($id)
    {
        global $wpdb;
        return $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM %i WHERE id = %d", $this->table, $id),
            ARRAY_A
        );
    }

    /**
     * Insert a new click
     *
     * @param array $data
     * @return int|false
     */
    public function create($data)
    {
        global $wpdb;
        $inserted = $wpdb->insert($this->table, $data);
        if ($inserted) {
            return $wpdb->insert_id;
        }
        return false;
    }

    /**
     * Update a click.
     *
     * @param int $id
     * @param array $data
     * @return bool|int
     */
    public function update($id, $data)
    {
        global $wpdb;
        return $wpdb->update($this->table, $data, ['id' => $id]);
    }

    /**
     * Delete a click.
     *
     * @param int $id
     * @return bool|int
     */
    public function delete($id)
    {
        global $wpdb;
        return $wpdb->delete($this->table, ['id' => $id]);
    }
}
