<?php
namespace Tshen\Controllers;
use Tshen\Database; use function Tshen\view; use function Tshen\redirect;

class StoreController {
    public function index() {
        $items = Database::run('SELECT * FROM products ORDER BY id DESC')->fetchAll();
        return view('store/index', ['title'=>'Store','items'=>$items]);
    }
    public function checkout() {
        if (!\Tshen\csrf_check()) { \Tshen\flash('error','Invalid request.'); return redirect('/store'); }
        $product_id = (int)($_POST['product_id'] ?? 0); $qty = (int)($_POST['qty'] ?? 1); $code = trim($_POST['code'] ?? '');
        $product = Database::run('SELECT * FROM products WHERE id=?', [$product_id])->fetch();
        if (!$product) redirect('/store');
        $price = $product['price'] * $qty;
        if ($code) {
            $discount = Database::run('SELECT percent FROM discount_codes WHERE code=?', [$code])->fetch();
            if ($discount) { $price = $price * (100 - (int)$discount['percent']) / 100; }
        }
        // Simulated checkout
        Database::run('INSERT INTO orders (product_id,qty,total_price) VALUES (?,?,?)', [$product_id,$qty,$price]);
        \Tshen\flash('success','Order placed.');
        redirect('/store');
    }
}