<?php
// /Controllers/CustomerController.php
namespace Controllers;
require_once __DIR__ . '/../_Core/bootstrap.php';

class CustomerController {
  protected $pdo;
  public function __construct(){
    $this->pdo = Database::getConnection();
  }

  public function list($page=1, $per=25, $params=[]){
    $offset = max(0, ($page-1)*$per);
    $q = $params['q'] ?? '';
    if ($q) {
      $stmt = $this->pdo->prepare("SELECT * FROM sd_customers WHERE name LIKE ? OR phone LIKE ? ORDER BY id DESC LIMIT ? OFFSET ?");
      $stmt->execute(["%$q%","%$q%",$per,$offset]);
    } else {
      $stmt = $this->pdo->prepare("SELECT * FROM sd_customers ORDER BY id DESC LIMIT ? OFFSET ?");
      $stmt->execute([$per,$offset]);
    }
    $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    return ['status'=>1,'data'=>$rows,'page'=>$page,'per'=>$per];
  }

  public function get($id){
    $stmt = $this->pdo->prepare("SELECT * FROM sd_customers WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $r = $stmt->fetch(\PDO::FETCH_ASSOC);
    if (!$r) return ['status'=>0,'error'=>'not_found'];
    return ['status'=>1,'data'=>$r];
  }

  public function create($input, $user_id){
    // Basic required fields: name, phone. Add fields as needed.
    $name = $input['name'] ?? '';
    $phone = $input['phone'] ?? '';
    if (!$name || !$phone) return ['status'=>0,'error'=>'missing_fields'];
    $stmt = $this->pdo->prepare("INSERT INTO sd_customers (name, phone, created_by, customer_status) VALUES (?, ?, ?, 'New')");
    $stmt->execute([$name, $phone, $user_id]);
    return ['status'=>1, 'insert_id'=>$this->pdo->lastInsertId()];
  }

  public function update($id, $input, $user_id){
    if (!$id) return ['status'=>0,'error'=>'missing_id'];
    $fields = [];
    $params = [];
    foreach (['name','phone','address','customer_status'] as $f){
      if (isset($input[$f])) { $fields[] = "$f = ?"; $params[] = $input[$f]; }
    }
    if (empty($fields)) return ['status'=>0,'error'=>'no_fields'];
    $params[] = $id;
    $sql = "UPDATE sd_customers SET " . implode(', ', $fields) . " WHERE id = ?";
    $stmt = $this->pdo->prepare($sql);
    $stmt->execute($params);
    return ['status'=>1,'updated_id'=>$id];
  }

  public function delete($id, $user_id){
    $stmt = $this->pdo->prepare("DELETE FROM sd_customers WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    return ['status'=>1,'deleted_id'=>$id];
  }
}
?>
