<?php
// Error reporting on karein taaki exact error pata chale
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

// --- DB CONNECTION (Inhe apni hosting ke hisaab se check karein) ---
define('DB_HOST', 'localhost');
define('DB_USER', 'kdsmf_eppd'); 
define('DB_PASS', '8DL!AesMeEt(%mgc');     
define('DB_NAME', 'kdsmf_epd');

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($conn->connect_error) {
    die(json_encode(['status' => 'error', 'message' => 'DB Connection Failed: ' . $conn->connect_error]));
}
$conn->set_charset('utf8mb4');

// Action handle karein (case-insensitive)
$action = isset($_GET['action']) ? strtolower($_GET['action']) : '';

$raw = file_get_contents('php://input');
$body = json_decode($raw, true) ?? [];
if(isset($body['action'])) $action = strtolower($body['action']);

// 1. Get Week Schedule
if ($action === 'week') {
    $schedule = [];
    for ($i = 0; $i < 7; $i++) {
        $date = date('Y-m-d', strtotime("+$i days"));
        $stmt = $conn->prepare("SELECT * FROM trade_day_config WHERE config_date = ?");
        $stmt->bind_param('s', $date);
        $stmt->execute();
        $res = $stmt->get_result()->fetch_assoc();
        
        $schedule[] = [
            'date' => $date,
            'day' => date('D, d M', strtotime($date)),
            'day_type' => $res ? $res['day_type'] : (date('N', strtotime($date)) >= 6 ? 'closed' : 'profit'),
            'profit_pct' => $res ? (float)$res['profit_pct'] : 0.04,
            'loss_pct' => $res ? (float)$res['loss_pct'] : 0.00,
            'note' => $res ? $res['note'] : '',
            'is_today' => ($date === date('Y-m-d'))
        ];
    }
    echo json_encode(['status' => 'success', 'schedule' => $schedule]);
    exit;
}

// 2. Set Day Config
if ($action === 'set_day') {
    if(!isset($body['date'], $body['day_type'])) {
        echo json_encode(['status' => 'error', 'message' => 'Missing data']);
        exit;
    }
    $date = $body['date'];
    $type = $body['day_type'];
    $pPct = (float)($body['profit_pct'] ?? 0.04);
    $lPct = (float)($body['loss_pct'] ?? 0.00);
    $note = $body['note'] ?? '';

    $stmt = $conn->prepare("INSERT INTO trade_day_config (config_date, day_type, profit_pct, loss_pct, note) 
                            VALUES (?, ?, ?, ?, ?) 
                            ON DUPLICATE KEY UPDATE day_type=VALUES(day_type), profit_pct=VALUES(profit_pct), loss_pct=VALUES(loss_pct), note=VALUES(note)");
    $stmt->bind_param('ssdds', $date, $type, $pPct, $lPct, $note);
    
    if($stmt->execute()) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => $stmt->error]);
    }
    exit;
}

// 3. Today's Status
if ($action === 'today') {
    $today = date('Y-m-d');
    $stmt = $conn->prepare("SELECT * FROM trade_day_config WHERE config_date = ?");
    $stmt->bind_param('s', $today);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    
    echo json_encode([
        'status' => 'success', 
        'day_type' => $res ? $res['day_type'] : 'profit', 
        'profit_pct' => $res ? (float)$res['profit_pct'] : 0.04, 
        'loss_pct' => $res ? (float)$res['loss_pct'] : 0, 
        'note' => $res ? $res['note'] : '', 
        'date' => $today
    ]);
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
?>