<?php
// api.php
session_start();
require_once __DIR__ . '/db.php';

header('Content-Type: application/json');

$action = isset($_GET['action']) ? $_GET['action'] : '';

// 1. Unauthenticated endpoints
if ($action === 'login') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
        exit;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    $id = isset($input['id']) ? trim($input['id']) : '';
    $pass = isset($input['pass']) ? trim($input['pass']) : '';
    
    if ($id === 'admin' && $pass === '123456') {
        $_SESSION['admin_logged_in'] = true;
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Access denied. Incorrect identifier or password.']);
    }
    exit;
}

if ($action === 'check_auth') {
    $loggedIn = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
    echo json_encode(['logged_in' => $loggedIn]);
    exit;
}

// GET state is open to the public (read-only)
if ($_SERVER['REQUEST_METHOD'] === 'GET' && empty($action)) {
    try {
        // Fetch settings
        $stmt = $pdo->query("SELECT * FROM settings WHERE id = 1 LIMIT 1");
        $settings = $stmt->fetch();
        
        if (!$settings) {
            // Re-run initialization fallback
            header('Location: db.php');
            exit;
        }
        
        // Fetch companies with img
        $stmt = $pdo->query("SELECT name, link, img FROM companies ORDER BY sort_order ASC");
        $companies = $stmt->fetchAll();
        
        // Fetch team
        $stmt = $pdo->query("SELECT name, role, img FROM team ORDER BY sort_order ASC");
        $team = $stmt->fetchAll();
        
        $state = [
            'title' => $settings['title'],
            'subtitle' => $settings['subtitle'],
            'aboutText' => $settings['about_text'],
            'address' => $settings['address'],
            'logo' => $settings['logo'],
            'video' => $settings['video'],
            
            // About Section & features
            'aboutTitle' => isset($settings['about_title']) ? $settings['about_title'] : 'Driving Progress Across Horizons',
            'aboutFeat1Title' => isset($settings['about_feat1_title']) ? $settings['about_feat1_title'] : 'Innovation First',
            'aboutFeat1Desc' => isset($settings['about_feat1_desc']) ? $settings['about_feat1_desc'] : 'Harnessing advanced operational dynamics to reshape platforms.',
            'aboutFeat1Icon' => isset($settings['about_feat1_icon']) ? $settings['about_feat1_icon'] : 'bi-cpu',
            'aboutFeat2Title' => isset($settings['about_feat2_title']) ? $settings['about_feat2_title'] : 'Global Standard',
            'aboutFeat2Desc' => isset($settings['about_feat2_desc']) ? $settings['about_feat2_desc'] : 'Delivering export-ready skill management globally.',
            'aboutFeat2Icon' => isset($settings['about_feat2_icon']) ? $settings['about_feat2_icon'] : 'bi-globe-americas',
            
            // Statistics board
            'stat1Value' => isset($settings['stat1_value']) ? $settings['stat1_value'] : '04+',
            'stat1Label' => isset($settings['stat1_label']) ? $settings['stat1_label'] : 'Operating Sectors',
            'stat2Value' => isset($settings['stat2_value']) ? $settings['stat2_value'] : '250+',
            'stat2Label' => isset($settings['stat2_label']) ? $settings['stat2_label'] : 'Expert Workforce',
            'stat3Value' => isset($settings['stat3_value']) ? $settings['stat3_value'] : '12+',
            'stat3Label' => isset($settings['stat3_label']) ? $settings['stat3_label'] : 'Global Partners',
            'stat4Value' => isset($settings['stat4_value']) ? $settings['stat4_value'] : '100%',
            'stat4Label' => isset($settings['stat4_label']) ? $settings['stat4_label'] : 'Compliance',
            
            // Custom Headers
            'companiesTitle' => isset($settings['companies_title']) ? $settings['companies_title'] : 'Our Commercial Enterprises',
            'teamTitle' => isset($settings['team_title']) ? $settings['team_title'] : 'Corporate Leadership',
            'contactTitle' => isset($settings['contact_title']) ? $settings['contact_title'] : 'Corporate HQ',
            
            // Hero buttons (A to Z dynamic elements)
            'heroBtn1Text' => isset($settings['hero_btn1_text']) ? $settings['hero_btn1_text'] : 'Explore Portfolio',
            'heroBtn1Link' => isset($settings['hero_btn1_link']) ? $settings['hero_btn1_link'] : '#companies',
            'heroBtn2Text' => isset($settings['hero_btn2_text']) ? $settings['hero_btn2_text'] : 'Get In Touch',
            'heroBtn2Link' => isset($settings['hero_btn2_link']) ? $settings['hero_btn2_link'] : '#contact',
            
            'companies' => $companies,
            'team' => $team
        ];
        
        echo json_encode($state);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// 2. Authenticated endpoints
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access. Please log in again.']);
    exit;
}

if ($action === 'save') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
        exit;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        echo json_encode(['success' => false, 'message' => 'Invalid input data.']);
        exit;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Update settings with all dynamic fields
        $stmt = $pdo->prepare("UPDATE settings SET 
            title = ?, subtitle = ?, about_text = ?, address = ?, logo = ?, video = ?,
            about_title = ?, about_feat1_title = ?, about_feat1_desc = ?, about_feat1_icon = ?,
            about_feat2_title = ?, about_feat2_desc = ?, about_feat2_icon = ?,
            stat1_value = ?, stat1_label = ?, stat2_value = ?, stat2_label = ?,
            stat3_value = ?, stat3_label = ?, stat4_value = ?, stat4_label = ?,
            companies_title = ?, team_title = ?, contact_title = ?,
            hero_btn1_text = ?, hero_btn1_link = ?, hero_btn2_text = ?, hero_btn2_link = ?
            WHERE id = 1");
        $stmt->execute([
            $input['title'],
            $input['subtitle'],
            $input['aboutText'],
            $input['address'],
            $input['logo'],
            $input['video'],
            
            $input['aboutTitle'],
            $input['aboutFeat1Title'],
            $input['aboutFeat1Desc'],
            $input['aboutFeat1Icon'],
            $input['aboutFeat2Title'],
            $input['aboutFeat2Desc'],
            $input['aboutFeat2Icon'],
            
            $input['stat1Value'],
            $input['stat1Label'],
            $input['stat2Value'],
            $input['stat2Label'],
            $input['stat3Value'],
            $input['stat3Label'],
            $input['stat4Value'],
            $input['stat4Label'],
            
            $input['companiesTitle'],
            $input['teamTitle'],
            $input['contactTitle'],
            
            $input['heroBtn1Text'],
            $input['heroBtn1Link'],
            $input['heroBtn2Text'],
            $input['heroBtn2Link']
        ]);
        
        // Update companies (delete existing and insert new with custom img column support)
        $pdo->exec("DELETE FROM companies");
        if (isset($input['companies']) && is_array($input['companies'])) {
            $stmtComp = $pdo->prepare("INSERT INTO companies (name, link, img, sort_order) VALUES (?, ?, ?, ?)");
            foreach ($input['companies'] as $index => $company) {
                $compImg = isset($company['img']) ? $company['img'] : null;
                $stmtComp->execute([$company['name'], $company['link'], $compImg, $index]);
            }
        }
        
        // Update team (delete existing and insert new)
        $pdo->exec("DELETE FROM team");
        if (isset($input['team']) && is_array($input['team'])) {
            $stmtTeam = $pdo->prepare("INSERT INTO team (name, role, img, sort_order) VALUES (?, ?, ?, ?)");
            foreach ($input['team'] as $index => $member) {
                $stmtTeam->execute([$member['name'], $member['role'], $member['img'], $index]);
            }
        }
        
        $pdo->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'reset') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
        exit;
    }
    
    try {
        $pdo->beginTransaction();
        
        // Truncate/delete
        $pdo->exec("DELETE FROM settings");
        $pdo->exec("DELETE FROM companies");
        $pdo->exec("DELETE FROM team");
        
        // Insert defaults
        $stmt = $pdo->prepare("INSERT INTO settings (
            id, title, subtitle, about_text, address, logo, video,
            about_title, about_feat1_title, about_feat1_desc, about_feat1_icon,
            about_feat2_title, about_feat2_desc, about_feat2_icon,
            stat1_value, stat1_label, stat2_value, stat2_label,
            stat3_value, stat3_label, stat4_value, stat4_label,
            companies_title, team_title, contact_title,
            hero_btn1_text, hero_btn1_link, hero_btn2_text, hero_btn2_link
        ) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            "Mahfuza Corporate Holdings",
            "Accelerating modern engineering, human deployment workflows, and comprehensive technical solutions globally.",
            "Our multi-disciplinary business entity operates across tech ecosystems, dynamic infrastructures, modern global operations, and human resource solutions. We build ecosystems centered around premium sustainability.",
            "Mohakhali C/A, Dhaka, Bangladesh",
            "https://placehold.co/80x80/0284c7/ffffff?text=M",
            "",
            "Driving Progress Across Horizons",
            "Innovation First",
            "Harnessing advanced operational dynamics to reshape platforms.",
            "bi-cpu",
            "Global Standard",
            "Delivering export-ready skill management globally.",
            "bi-globe-americas",
            "04+", "Operating Sectors",
            "250+", "Expert Workforce",
            "12+", "Global Partners",
            "100%", "Compliance",
            "Our Commercial Enterprises",
            "Corporate Leadership",
            "Corporate HQ",
            "Explore Portfolio", "#companies",
            "Get In Touch", "#contact"
        ]);
        
        $stmtComp = $pdo->prepare("INSERT INTO companies (name, link, img, sort_order) VALUES (?, ?, ?, ?)");
        $stmtComp->execute(["Smart IT Solution", "https://smartitsolution-demo.com", null, 0]);
        $stmtComp->execute(["Mahfuza Overseas Employment", "https://mahfuzaoverseas-demo.com", null, 1]);
        
        $stmtTeam = $pdo->prepare("INSERT INTO team (name, role, img, sort_order) VALUES (?, ?, ?, ?)");
        $stmtTeam->execute(["Ibrahim Khalil", "Chief Executive Officer / Managing Director", "https://placehold.co/300x300/0f172a/ffffff?text=IK", 0]);
        $stmtTeam->execute(["Rahman Chowdhury", "Head of Technical Architecture", "https://placehold.co/300x300/1e293b/ffffff?text=RC", 1]);
        
        $pdo->commit();
        
        // Return default state mapping
        $defaultState = [
            'title' => "Mahfuza Corporate Holdings",
            'subtitle' => "Accelerating modern engineering, human deployment workflows, and comprehensive technical solutions globally.",
            'aboutText' => "Our multi-disciplinary business entity operates across tech ecosystems, dynamic infrastructures, modern global operations, and human resource solutions. We build ecosystems centered around premium sustainability.",
            'address' => "Mohakhali C/A, Dhaka, Bangladesh",
            'logo' => "https://placehold.co/80x80/0284c7/ffffff?text=M",
            'video' => "",
            
            'aboutTitle' => "Driving Progress Across Horizons",
            'aboutFeat1Title' => "Innovation First",
            'aboutFeat1Desc' => "Harnessing advanced operational dynamics to reshape platforms.",
            'aboutFeat1Icon' => "bi-cpu",
            'aboutFeat2Title' => "Global Standard",
            'aboutFeat2Desc' => "Delivering export-ready skill management globally.",
            'aboutFeat2Icon' => "bi-globe-americas",
            
            'stat1Value' => "04+",
            'stat1Label' => "Operating Sectors",
            'stat2Value' => "250+",
            'stat2Label' => "Expert Workforce",
            'stat3Value' => "12+",
            'stat3Label' => "Global Partners",
            'stat4Value' => "100%",
            'stat4Label' => "Compliance",
            
            'companiesTitle' => "Our Commercial Enterprises",
            'teamTitle' => "Corporate Leadership",
            'contactTitle' => "Corporate HQ",
            
            'heroBtn1Text' => "Explore Portfolio",
            'heroBtn1Link' => "#companies",
            'heroBtn2Text' => "Get In Touch",
            'heroBtn2Link' => "#contact",
            
            'companies' => [
                ['name' => "Smart IT Solution", 'link' => "https://smartitsolution-demo.com", 'img' => null],
                ['name' => "Mahfuza Overseas Employment", 'link' => "https://mahfuzaoverseas-demo.com", 'img' => null]
            ],
            'team' => [
                ['name' => "Ibrahim Khalil", 'role' => "Chief Executive Officer / Managing Director", 'img' => "https://placehold.co/300x300/0f172a/ffffff?text=IK"],
                ['name' => "Rahman Chowdhury", 'role' => "Head of Technical Architecture", 'img' => "https://placehold.co/300x300/1e293b/ffffff?text=RC"]
            ]
        ];
        
        echo json_encode(['success' => true, 'state' => $defaultState]);
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

echo json_encode(['success' => false, 'message' => 'Invalid action.']);
