#!/usr/bin/env python3
import requests
import time
import io
import struct
import zlib

PROXY = {
    'http': 'http://b04dd480860a80d0:VJvorQIeLmBSK1G9@res.proxy-seller.com:10005',
    'https': 'http://b04dd480860a80d0:VJvorQIeLmBSK1G9@res.proxy-seller.com:10005'
}

def create_real_png():
    """Create a real valid 1x1 PNG"""
    def png_chunk(type_code, data):
        chunk_type = type_code.encode('latin-1')
        chunk_len = struct.pack('>I', len(data))
        chunk_crc = struct.pack('>I', zlib.crc32(chunk_type + data) & 0xffffffff)
        return chunk_len + chunk_type + data + chunk_crc
    
    signature = b'\x89PNG\r\n\x1a\n'
    
    # IHDR: 1x1, 8-bit RGB
    ihdr_data = struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0)
    ihdr = png_chunk('IHDR', ihdr_data)
    
    # IDAT: Compressed pixel data (filter byte + RGB)
    raw_data = b'\x00\xff\xff\xff'  # filter byte + white pixel
    compressed = zlib.compress(raw_data, 9)
    idat = png_chunk('IDAT', compressed)
    
    # IEND
    iend = png_chunk('IEND', b'')
    
    return signature + ihdr + idat + iend

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
}

session = requests.Session()

# Get main page first
print("[*] Getting main page...")
resp = session.get("https://pohon.disperkim.semarangkota.go.id/main", headers=headers, proxies=PROXY, verify=False, timeout=30)
print(f"[*] Status: {resp.status_code}")

time.sleep(2)

# Create valid PNG
png_content = create_real_png()
print(f"[*] PNG created: {len(png_content)} bytes")
print(f"[*] PNG header: {png_content[:8].hex()}")

# Test upload
print("\n[*] Testing upload...")
files = {
    'userfile': ('image.png', io.BytesIO(png_content), 'image/png')
}

data = {
    'pelapor_nama': 'TestUser123',
    'pelapor_alamat': 'Test Alamat 123',
    'pelapor_phone': '081234567890',
    'pohon_lokasi': 'Test Lokasi Jakarta',
    'pohon_keterangan': 'Test Keterangan Pohon',
}

try:
    resp = session.post("https://pohon.disperkim.semarangkota.go.id/main/laporan_input", 
                       files=files, data=data, headers=headers, 
                       proxies=PROXY, verify=False, timeout=60, allow_redirects=True)
    print(f"[*] Status: {resp.status_code}")
    print(f"[*] Final URL: {resp.url}")
    
    # Check flash messages in session
    print(f"\n[*] Checking for success/error messages...")
    if 'success' in resp.text.lower() or 'berhasil' in resp.text.lower():
        print("[+] SUCCESS message found!")
    elif 'error' in resp.text.lower() or 'gagal' in resp.text.lower():
        print("[-] ERROR message found")
        
    # Try to find form in response
    if '<form' in resp.text:
        print("[*] Form found in response - upload might have failed")
        
    print(f"\n[*] Response contains {len(resp.text)} chars")
    
except Exception as e:
    print(f"[-] Error: {e}")

# Check laporan page
print("\n[*] Checking laporan list...")
time.sleep(2)
resp = session.get("https://pohon.disperkim.semarangkota.go.id/laporan", headers=headers, proxies=PROXY, verify=False, timeout=30)
if 'TestUser123' in resp.text:
    print("[+] Our test entry found!")
else:
    print("[-] Test entry not found in laporan list")

