<?php
// Enable detailed error reporting
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/debug.log');
error_reporting(E_ALL | E_STRICT);

// Start session for state management
session_start();

// Clear output buffer
ob_start();
header('Access-Control-Allow-Origin: *');

// Debug endpoint: ?debug=1 to read debug.log
if (isset($_GET['debug']) && $_GET['debug'] === '1') {
    header('Content-Type: text/plain');
    if (file_exists(__DIR__ . '/debug.log')) {
        echo file_get_contents(__DIR__ . '/debug.log');
    } else {
        echo "No debug log found.";
    }
    ob_end_flush();
    exit;
}

// Check for required date parameters
if (!isset($_GET['date1']) || !isset($_GET['date2'])) {
    file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Missing parameters: " . print_r($_GET, true) . "\n", FILE_APPEND);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Missing date parameters, contact Yash for details']);
    ob_end_flush();
    exit;
}

$date1 = $_GET['date1'];
$date2 = $_GET['date2'];

// Validate date format (DD-MM-YYYY)
if (!preg_match('/^\d{2}-\d{2}-\d{4}$/', $date1) || !preg_match('/^\d{2}-\d{2}-\d{4}$/', $date2)) {
    file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Invalid date format: date1=$date1, date2=$date2\n", FILE_APPEND);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Invalid date format, contact Yash for details']);
    ob_end_flush();
    exit;
}

// If session not initialized or dates don't match (to prevent mixing sessions), initialize
if (!isset($_SESSION['initialized']) || $_SESSION['date1'] !== $date1 || $_SESSION['date2'] !== $date2) {
    // Autodetect domain
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    $domain = $_SERVER['HTTP_HOST'];
    $strikes_url = "{$protocol}{$domain}/api/get_strikes_nse.php?date1=$date1&date2=$date2";

    // Fetch strike URLs from the get_strikes_nse.php endpoint
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $strikes_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
        'Accept: application/json, text/plain, */*',
        'Accept-Language: en-US,en;q=0.9',
        'Accept-Encoding: gzip, deflate',
    ]);

    $strikes_response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    // Log strikes response
    file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Strikes URL: $strikes_url\nHTTP Code: $httpCode\nResponse (base64): " . base64_encode($strikes_response) . "\nError: $error\n", FILE_APPEND);

    // Check for errors in strikes fetch
    if ($error || $httpCode !== 200) {
        header('Content-Type: application/json');
        echo json_encode(['error' => "Failed to fetch strikes (HTTP $httpCode, Error: $error), contact Yash for details"]);
        ob_end_flush();
        exit;
    }

    // Parse strikes JSON
    $strikes_data = json_decode($strikes_response, true);
    if (json_last_error() !== JSON_ERROR_NONE || !isset($strikes_data['data']) || empty($strikes_data['data'])) {
        file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Strikes JSON Error: " . json_last_error_msg() . "\n", FILE_APPEND);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Invalid strikes data, contact Yash for details']);
        ob_end_flush();
        exit;
    }

    // Store URLs in session
    $_SESSION['urls'] = array_map(function($strike) {
        return $strike['STRIKEURL'];
    }, $strikes_data['data']);
    $_SESSION['combined_data'] = [];
    $_SESSION['total'] = count($_SESSION['urls']);
    $_SESSION['current'] = 0;
    $_SESSION['date1'] = $date1;
    $_SESSION['date2'] = $date2;
    $_SESSION['cookie_file'] = __DIR__ . '/nse_cookies_' . session_id() . '.txt';
    $_SESSION['initialized'] = true;

    // Fetch initial cookies
    if (!fetchNSECookies($_SESSION['cookie_file'])) {
        file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Failed to fetch NSE cookies during initialization\n", FILE_APPEND);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Failed to establish NSE session, contact Yash for details']);
        session_destroy();
        ob_end_flush();
        exit;
    }
}

// Function to fetch NSE cookies
function fetchNSECookies($cookie_file) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.nseindia.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.9',
        'Accept-Encoding: gzip, deflate',
        'Connection: keep-alive',
        'Upgrade-Insecure-Requests: 1',
    ]);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) {
        file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Cookie fetch error: $error\n", FILE_APPEND);
        return false;
    }
    return true;
}

// Process up to 3 URLs per request if not complete
if ($_SESSION['current'] < $_SESSION['total']) {
    $batch_size = min(3, $_SESSION['total'] - $_SESSION['current']); // Process up to 3 URLs
    for ($i = 0; $i < $batch_size; $i++) {
        $url = $_SESSION['urls'][$_SESSION['current']];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $_SESSION['cookie_file']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
            'Accept: application/json, text/plain, */*',
            'Accept-Language: en-US,en;q=0.9',
            'Accept-Encoding: gzip, deflate',
            'Referer: https://www.nseindia.com/',
            'X-Requested-With: XMLHttpRequest',
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        // Log response details
        file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - URL: $url\nHTTP Code: $httpCode\nResponse (base64): " . base64_encode($response) . "\nError: $error\n", FILE_APPEND);

        if ($error || $httpCode !== 200) {
            $_SESSION['combined_data'][] = ['url' => $url, 'error' => "API request failed (HTTP $httpCode, Error: $error)"];
        } else {
            $data = json_decode($response, true);
            if (json_last_error() !== JSON_ERROR_NONE || !isset($data['data']) || empty($data['data'])) {
                file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - JSON Error for $url: " . json_last_error_msg() . "\n", FILE_APPEND);
                $_SESSION['combined_data'][] = ['url' => $url, 'error' => 'Invalid or empty data'];
            } else {
                $_SESSION['combined_data'][] = ['url' => $url, 'data' => $data['data']];
            }
        }

        $_SESSION['current']++;
    }
}

// Output as HTML for auto-reload functionality
header('Content-Type: text/html');
echo "<!DOCTYPE html><html><head><title>Processing Data</title></head><body>";
echo "<h1>Processing Data for $date1</h1>";
echo "<p>Processed {$_SESSION['current']} of {$_SESSION['total']}</p>";

if ($_SESSION['current'] < $_SESSION['total']) {
    echo "<p>Reloading in 0.5 seconds to process next...</p>";
    echo "<script>setTimeout(function(){ location.reload(); }, 500);</script>";
} else {
    // Ensure the data folder exists
    $data_dir = __DIR__ . '/data';
    if (!is_dir($data_dir)) {
        if (!mkdir($data_dir, 0755, true)) {
            file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Failed to create data directory: $data_dir\n", FILE_APPEND);
            echo "<p style='color: red;'>Failed to create data directory, contact Yash for details</p>";
            session_destroy();
            ob_end_flush();
            exit;
        }
    }

    // Save combined data to JSON file in the data folder
    $output_file = $data_dir . '/' . $date1 . '.json';
    if (file_put_contents($output_file, json_encode(['results' => $_SESSION['combined_data']], JSON_PRETTY_PRINT)) === false) {
        file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - Failed to write to $output_file\n", FILE_APPEND);
        echo "<p style='color: red;'>Failed to save data, contact Yash for details</p>";
    } else {
        echo "<p style='color: green;'>Success: Data saved to $output_file</p>";
    }

    // Clean up
    @unlink($_SESSION['cookie_file']);
    session_destroy();
}

echo "</body></html>";

ob_end_flush();
?>