<?php
require_once __DIR__ . '/../config/database.php';

class CustomerController {

    private $conn;

    public function __construct() {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->conn->connect_error) {
            die("Error de conexión: " . $this->conn->connect_error);
        }
    }

    public function findOrCreateCustomer($phone) {
        $stmt = $this->conn->prepare("SELECT id FROM customers WHERE phone = ?");
        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            return $result->fetch_assoc()['id'];
        } else {
            $referral_code = $this->generateReferralCode($phone);
            $stmt = $this->conn->prepare("INSERT INTO customers (phone, referral_code) VALUES (?, ?)");
            $stmt->bind_param("ss", $phone, $referral_code);
            $stmt->execute();
            return $stmt->insert_id;
        }
    }

    private function generateReferralCode($phone) {
        $initials = substr($phone, -4);
        $count = $this->conn->query("SELECT COUNT(*) as count FROM customers")->fetch_assoc()['count'];
        return $initials . ($count + 1);
    }

    public function addPoints($customerId, $points, $reason) {
        $this->conn->query("UPDATE customers SET points = points + $points WHERE id = $customerId");
        $stmt = $this->conn->prepare("INSERT INTO points_log (customer_id, points, reason) VALUES (?, ?, ?)");
        $stmt->bind_param("iis", $customerId, $points, $reason);
        $stmt->execute();
    }
    public function getInactiveCustomers() {
        $result = $this->conn->query("SELECT * FROM customers WHERE last_purchase_date < DATE_SUB(NOW(), INTERVAL 30 DAY)");
        $customers = [];
        while ($row = $result->fetch_assoc()) {
            $customers[] = $row;
        }
        return $customers;
    }
}
?>