<?php

    $submit = getuserdata('submit');
    $actiune = getuserdata('actiune');
    $id = getuserdata('id', 0);
    $medic = getuserdata('medic', '');
    $functia = getuserdata('functia', '');
    $mesaj = getuserdata('mesaj', '');
    $imagine = getuserdata('imagine', '');
    $publicat = getuserdata('publicat', 1);
    $stergeimg = getuserdata('stergeimg', 0);
    
    function imageresize($image, $maxwidth, $maxheight)
    {
        $w = imagesx($image);
        $h = imagesy($image);
        $procw = (float)$maxwidth / (float)$w;
        $proch = (float)$maxheight / (float)$h;
        $proc = min(array($procw, $proch));
        if ($proc > 1) $proc = 1;
        $new_width = (int)($w * $proc);
        $new_height = (int)($h * $proc);
        $new_image = imagecreatetruecolor($new_width, $new_height);
        imagealphablending($new_image, false);
        imagesavealpha($new_image, true);
        $transparent_colors = imagecolorsforindex($image, $transparent_index);
        $transparent_index = imagecolorallocatealpha($new_image, $transparent_colors['red'], $transparent_colors['green'], 
                                                     $transparent_colors['blue'], $transparent_colors['alpha']);
        imagefill($new_image, 0, 0, $transparent_index);
        imagecopyresampled($new_image, $image, $bordersizeh, $bordersizev, 0, 0, $new_width, $new_height, $w, $h);
        return $new_image;
    }
    
    switch ($actiune)
    {
        case 'do_editare':
            if ($submit != 'Salvează')
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
            $q = mysql_query("SELECT * FROM testimoniale WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                mysql_query("UPDATE testimoniale SET medic = '$medic', functia = '$functia', mesaj = '$mesaj', publicat = $publicat WHERE id = $id");
                $eroare = mysql_error();
            }
            else
            {
                $qm = mysql_query("SELECT MAX(nr_crt) AS nr FROM testimoniale");
                if ($rm = mysql_fetch_assoc($qm)) $nrcrt = ((int)$rm['nr']) + 1;
                                             else $nrcrt = 1; 
                mysql_query("INSERT INTO testimoniale (medic, functia, mesaj, publicat, nr_crt) VALUES ('$medic', '$functia', '$mesaj', $publicat, $nrcrt)");
                $id = mysql_insert_id();
                $eroare = mysql_error();
            }
            // Daca se bifeaza stergerea, il sterg
            if ( (!$eroare) && ($stergeimg) )
            {
                $q = mysql_query("SELECT * FROM testimoniale WHERE id = $id");
                if ($r = mysql_fetch_assoc($q))
                {
                    if ($r['imagine'])
                    {
                        unlink($imagespath.$r['imagine']);
                        mysql_query("UPDATE testimoniale SET imagine = NULL WHERE id = $id");
                    }
                }
            }
            // Incarc si fisierul
            if ( (!$eroare) && (isset($_FILES['imagine'])) )
            {
                if ($_FILES['imagine']['error'] == UPLOAD_ERR_OK)
                {
                    $filename = $_FILES['imagine']['name'];
                    $i = 0;
                    while (file_exists($imagespath.$filename))
                    {
                        $extpos = strrpos($filename, '.');
                        $filename = substr($filename, 0, $extpos).(++$i).strrchr($filename, '.');
                    }
                    move_uploaded_file($_FILES['imagine']['tmp_name'], $imagespath.$filename);
                    list($w, $h) = getimagesize($imagespath.$filename);
                    $info = getimagesize($imagespath.$filename);
                    switch ($info[2])
                    {
                        case IMAGETYPE_GIF:
                            $sourcelayer = imagecreatefromgif($imagespath.$filename);
                            $dest = imageresize($sourcelayer, 100, 117);
                            imagegif($dest, $imagespath.$filename);
                            break;
                        case IMAGETYPE_JPEG:
                            $sourcelayer = imagecreatefromjpeg($imagespath.$filename);
                            $dest = imageresize($sourcelayer, 100, 117);
                            imagejpeg($dest, $imagespath.$filename);
                            break;
                        case IMAGETYPE_PNG:
                            $sourcelayer = imagecreatefrompng($imagespath.$filename);
                            $dest = imageresize($sourcelayer, 100, 117);
                            imagepng($dest, $imagespath.$filename);
                            break;
                        case IMAGETYPE_WBMP:
                            $sourcelayer = imagecreatefromwbmp($imagespath.$filename);
                            $dest = imageresize($sourcelayer, 100, 117);
                            imagewbmp($dest, $imagespath.$filename);
                            break;
                        case IMAGETYPE_XBM:
                            $sourcelayer = imagecreatefromxbm($imagespath.$filename);
                            $dest = imageresize($sourcelayer, 100, 117);
                            imagexbm($dest, $imagespath.$filename);
                            break;
                        default:
                            $eroare = "Acest tip de fișier nu este suportat.";
                            $filename = '';
                            exit;
                    }
                    if ($filename) mysql_query("UPDATE testimoniale SET imagine = '$filename' WHERE id = $id");
                }
                else $eroare = 'Fișierul nu a putut fi încărcat pe server!';    
            }
            if (!$eroare)
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
        case 'editare':
            writepagetitle();
            writepagetop();
            writeinfolayer();
            $q = mysql_query("SELECT * FROM testimoniale WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                $medic = $r['medic'];
                $functia = $r['functia'];
                $mesaj = $r['mesaj'];
                $publicat = $r['publicat'];
                $imagine = $r['imagine'];
            }
            echo "<form action='{$_SERVER['PHP_SELF']}' method='POST' enctype='multipart/form-data'>";
            echo "<input type='hidden' name='actiune' value='do_editare'>";
            echo "<input type='hidden' name='pagina' value='$pagina'>";
            echo "<input type='hidden' name='id' value='{$r['id']}'>";
            echo "<center><table class='formular'>";
            echo "<tr><th>Medic:</th><td><input type='text' name='medic' value='$medic'></td></tr>";
            echo "<tr><th>Functia:</th><td><input type='text' name='functia' value='$functia'></td></tr>";
            echo "<tr><th>Mesaj:</th><td><span class='editor'>";
            echo "<textarea name='mesaj' style='height: 400px'>$mesaj</textarea></span>  </td></tr>";
            echo "<tr><th>Poza:</th><td>";
            if ($imagine)
            {
                echo "<img src='{$imagesroot}{$r['imagine']}' width='100' height='117'>";
                echo "<br><label for='stergeimg'>".
			         "<input type='checkbox' style='width: auto; border: none' name='stergeimg' id='stergeimg' value='1'>".
				     " Șterge</label><br><br>sau alege o altă imagine:<br>";
            } 
            echo "<input type='file' name='imagine'></td></tr>";
            echo "<tr><th>Opțiuni</th><td><label for='publicat'>".
			     "<input type='checkbox' style='width: auto; border: none' name='publicat' id='publicat' value='1'".
				 (($publicat == 1)?' checked':'')."> Publicat pe site</label></td></tr>";
            echo "<tr><td>&nbsp;</td><td class='butoane'>";
            echo "<input type='submit' name='submit' id='save' value='Salvează' class='buton_salveaza'>";
            echo "<input type='submit' name='submit' id='cancel' value='Anulează' class='buton_anuleaza'>";
            echo "</td></tr></table></center></form>";
            writepagebottom();
            exit;
        case 'do_stergere':
            if ($submit != 'Șterge')
            {
                header("Location: {$_SERVER['PHP_SELF']}");
                exit;
            }
            $q = mysql_query("SELECT * FROM testimoniale WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                if ($r['imagine']) unlink($imagespath.$r['imagine']);
                mysql_query("UPDATE testimoniale SET nr_crt = nr_crt - 1 WHERE nr_crt > {$r['nr_crt']}");
                mysql_query("DELETE FROM testimoniale WHERE id = $id");
                $eroare = mysql_error();
            }
            else
            {
                $eroare = 'Testimonialul selectat nu poate fi accesat';
            }
            if (!$eroare)
            {
                header("Location: {$_SERVER['PHP_SELF']}?pagina=$pagina");
                exit;
            }
        case 'stergere':
            $q = mysql_query("SELECT * FROM testimoniale WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                writepagetitle();
                writepagetop();
                writeinfolayer();
                $medic = $r['medic'];
                echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
                echo "<input type='hidden' name='actiune' value='do_stergere'>";
                echo "<input type='hidden' name='pagina' value='$pagina'>";
                echo "<input type='hidden' name='id' value='{$r['id']}'>";
                echo "<center><table class='formular'>";
                echo "<tr><th>Sigur doriți să ștergeți testimonialul '$medic'?</th></tr>";
                echo "<tr><td class='butoane'>";
                echo "<input type='submit' name='submit' id='save' value='Șterge'>";
                echo "<input type='submit' name='submit' id='cancel' value='Anulează'>";
                echo "</td></tr></table></center></form>";
                writepagebottom();
                exit;
            }
        case 'do_down':
            $q = mysql_query("SELECT * FROM testimoniale WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                $q1 = mysql_query("SELECT * FROM testimoniale WHERE nr_crt > {$r['nr_crt']} ORDER BY nr_crt ASC LIMIT 0, 1");
                if ($r1 = mysql_fetch_assoc($q1))
                {
                    mysql_query("UPDATE testimoniale SET nr_crt = {$r['nr_crt']} WHERE id = {$r1['id']}");
                    mysql_query("UPDATE testimoniale SET nr_crt = {$r1['nr_crt']} WHERE id = {$r['id']}");
                }
            }
            break;
        case 'do_up':
            $q = mysql_query("SELECT * FROM testimoniale WHERE id = $id");
            if ($r = mysql_fetch_assoc($q))
            {
                $q1 = mysql_query("SELECT * FROM testimoniale WHERE nr_crt < {$r['nr_crt']} ORDER BY nr_crt DESC LIMIT 0, 1");
                if ($r1 = mysql_fetch_assoc($q1))
                {
                    mysql_query("UPDATE testimoniale SET nr_crt = {$r['nr_crt']} WHERE id = {$r1['id']}");
                    mysql_query("UPDATE testimoniale SET nr_crt = {$r1['nr_crt']} WHERE id = {$r['id']}");
                }
            }
            break;
    }

    writepagetitle();
    writepagetop();
    writeinfolayer();
    echo "<span class='articol'>";
    echo "<h1>Testimoniale</h1>";
    echo "<table><tr><th style='width: 500px'>Medic</th><th>Acțiuni</th></tr>";
    $q = mysql_query("SELECT * FROM testimoniale ORDER BY nr_crt ASC");
    while ($r = mysql_fetch_assoc($q))
    {
        echo "<tr><td>{$r['medic']}</td>";
        echo "<td class='butoane'>";
        echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
        echo "<input type='hidden' name='actiune' value='editare'>";
        echo "<input type='hidden' name='pagina' value='$pagina'>";
        echo "<input type='hidden' name='id' value='{$r['id']}'>";
        echo "<input type='submit' name='submit' id='edit' value='Editează'>";
        echo "</form>";
        echo "<form action='{$_SERVER['PHP_SELF']}' method='POST'>";
        echo "<input type='hidden' name='actiune' value='stergere'>";
        echo "<input type='hidden' name='pagina' value='$pagina'>";
        echo "<input type='hidden' name='id' value='{$r['id']}'>";
        echo "<input type='submit' name='submit' id='delete' value='Șterge'>";
        echo "</form>";
        echo "<a href='{$_SERVER['PHP_SELF']}?pagina=$pagina&actiune=do_up&id={$r['id']}' style='padding: 3px 2px' title='sus'>".
             "<img src='{$imagesroot}btnimg_up.png' alt='sus'></a>";
        echo "<a href='{$_SERVER['PHP_SELF']}?pagina=$pagina&actiune=do_down&id={$r['id']}' style='padding: 3px 2px' title='jos'>".
             "<img src='{$imagesroot}btnimg_down.png' alt='jos'></a>";
        echo "</td></tr>";
    }
    echo "</table>";
    echo "<form action='{$_SERVER['PHP_SELF']}' method='POST' class='butoane'>";
    echo "<input type='hidden' name='actiune' value='editare'>";
    echo "<input type='hidden' name='pagina' value='$pagina'>";
    echo "<input type='hidden' name='id' value='0'>";
    echo "<input type='submit' name='submit' id='add' value='Adaugă'>";
    echo "</form></span>";    
    writepagebottom();
?>