<?php
// competitor_activity_crud.php - CRUD for competitor activity
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');
$pdo = require __DIR__ . '/../config/db.php';
$action = $_POST['action'] ?? $_GET['action'] ?? '';
function json_response($data)
{
    echo json_encode($data);
    exit;
}
if ($action === 'get') {
    $id = $_POST['id'] ?? $_GET['id'] ?? null;
    if (!$id) json_response(['error' => 'Missing id']);
    $stmt = $pdo->prepare('SELECT * FROM comp_activity WHERE id = ?');
    $stmt->execute([$id]);
    $activity = $stmt->fetch();
    json_response(['activity' => $activity]);
}
if ($action === 'add' || $action === 'update') {
    $site = $_POST['site_id'] ?? null;
    $competitor = $_POST['competitor_id'] ?? null;
    $airing_time = $_POST['airing_time'] ?? null;
    $estimate_end = $_POST['estimate_end'] ?? null;
    $side_no = isset($_POST['side_no']) ? intval($_POST['side_no']) : null;
    $id = $_POST['activity_id'] ?? null;
    // Handle image upload
    $image_comp = null;
    if (isset($_FILES['image_comp']) && $_FILES['image_comp']['tmp_name']) {
        $ext = pathinfo($_FILES['image_comp']['name'], PATHINFO_EXTENSION);
        $basename = pathinfo($_FILES['image_comp']['name'], PATHINFO_FILENAME);
        $filename = time() . '_comp_' . preg_replace('/[^A-Za-z0-9_-]/', '', $basename) . '.' . $ext;
        $target = __DIR__ . '/../media/competitor/' . $filename;
        if (move_uploaded_file($_FILES['image_comp']['tmp_name'], $target)) {
            $image_comp = $filename;
        }
    }
    if ($action === 'add') {
        $stmt = $pdo->prepare('INSERT INTO comp_activity (competitor_id, site, side_no, image_comp, airing_time, estimate_end) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $competitor,
            $site,
            $side_no,
            $image_comp,
            $airing_time,
            $estimate_end
        ]);
        json_response(['success' => true]);
    } else {
        // update
        $set = 'competitor_id = ?, site = ?, side_no = ?, airing_time = ?, estimate_end = ?';
        $params = [$competitor, $site, $side_no, $airing_time, $estimate_end];
        if ($image_comp) {
            $set .= ', image_comp = ?';
            $params[] = $image_comp;
        }
        $params[] = $id;
        $stmt = $pdo->prepare("UPDATE comp_activity SET $set WHERE id = ?");
        $stmt->execute($params);
        json_response(['success' => true]);
    }
}
if ($action === 'delete') {
    $id = $_POST['id'] ?? $_GET['id'] ?? null;
    if (!$id) json_response(['error' => 'Missing id']);
    $stmt = $pdo->prepare('DELETE FROM comp_activity WHERE id = ?');
    $stmt->execute([$id]);
    json_response(['success' => true]);
}
json_response(['error' => 'Invalid action']);
